Exemple #1
0
//客户端界面
void mainPage(){
	while(1){
		printf("  欢迎使用迷你ATM机\n");
		printf("---------------------\n");
		printf("[1] 开户");
		printf("      [2] 销户\n");
		printf("[3] 存钱");
		printf("      [4] 取钱\n");
		printf("[5] 查询");
		printf("      [6] 转账\n");
		printf("[0] 退出\n");
		printf("---------------------\n");
		printf("请选择:\n");
		int num = 0;
		scanf("%d",&num);
		switch(num){
			case 1:createUser();break;
			case 2:destroyUser();break;
			case 3:saveMoney();break;
			case 4:getMoney();break;
			case 5:checkMoney();break;
			case 6:moveMoney();break;
			case 0:printf("谢谢使用,再见!\n");return ;
			default:printf("输入错误\n");
		}
	}
}
Exemple #2
0
    std::vector<User> getUsers(const Api &api,
                               const std::vector<std::string> &ids,
                               const std::vector<std::string> &logins)
    {
        if(ids.empty() && logins.empty())
        {
            throw TwitchException("Either login or user id should be specified!");
        }

        auto response = api.reqWait().get(getUsersUri(ids, logins));

        std::vector<User> result;

        if(response.has_array_field("data"))
        {
            auto data = response.at("data").as_array();

            result.reserve(data.size());

            for(const auto& user: data)
            {
                result.push_back(createUser(user));

            }
            return result;
        }
    }
/**
 * Do the actual work of createFAQ()
 */
QByteArray SnippetCreator::createQuestions(const QJsonObject& joAPI) const
{
    QJsonArray jaQuestions = joAPI.value("questions").toArray();
    Template tQuestions("./Templates/Questions.html");

    tQuestions.setValue("StyleSheet", "http://localhost:8080/Templates/FAQs.css");

    // for each question
    for(QJsonArray::Iterator itq = jaQuestions.begin(); itq != jaQuestions.end(); ++itq)
    {
        // the question itself
        QJsonObject joQuestion = (*itq).toObject();
        Template tQuestion("./Templates/Question.html");
        tQuestion.setValue("Title", joQuestion.value("question").toString());

        // users
        QJsonArray users = joQuestion.value("users").toArray();
        for(QJsonArray::Iterator itu = users.begin(); itu != users.end(); ++itu)
        {
            QJsonObject joUser = (*itu).toObject();
            Template tInterestedUser("./Templates/InterestedUser.html");
            tInterestedUser.setValue("User", createUser(joUser));
            tQuestion.addValue("InterestedUser", tInterestedUser.toHTML());
        }

        // answers
        QJsonArray joAnswers = joQuestion.value("answers").toArray();
        if(joAnswers.isEmpty())
        {
            Template tAnswer("./Templates/Answer.html");
            tAnswer.setValue("Title", "Not answered!");
            tQuestion.addValue("Answer", tAnswer.toHTML());
        }
        else {
            for(QJsonArray::Iterator ita = joAnswers.begin(); ita != joAnswers.end(); ++ita)
            {
                QJsonObject joAnswer = (*ita).toObject();
                QString link  = joAnswer.value("link") .toString();
                QString title = joAnswer.value("title").toString();
                if(title.isEmpty())
                    title = "Link";

                Template tAnswer("./Templates/Answer.html");
                tAnswer.setValue("Title", title);                // format answer
                tAnswer.setValue("Link",  link);
                tQuestion.addValue("Answer", tAnswer.toHTML());  // add to the question
            }
        }
        tQuestions.addValue("Question", tQuestion.toHTML());     // add the question
    }
    return tQuestions.toHTML();
}
/**
 * Create the related users section of a profile page
 */
QByteArray SnippetCreator::createRelatedUsers(const QJsonObject& joProfile) const
{
    Template tUsers("./Templates/RelatedUsers.html");
    QJsonArray jaUsers = joProfile.value("relatedusers").toArray();
    for(QJsonArray::Iterator it = jaUsers.begin(); it != jaUsers.end(); ++it)
    {
        QJsonObject joUser = (*it).toObject();
        Template tRelatedUser("./Templates/RelatedUser.html");
        tRelatedUser.setValue("User", createUser(joUser));
        tUsers.addValue("RelatedUser", tRelatedUser.toHTML());
    }
    return tUsers.toHTML();
}
Exemple #5
0
    User updateUserDescription(const Api &api, const std::string &newDescription)
    {
        web::uri_builder builder("helix/users");

        builder.append_query("description", newDescription);

        auto result = api.reqWait().put(builder.to_uri(),AuthScope::USER_EDIT);

        if(result.has_array_field("data"))
        {
            return createUser(result.at("data").as_array()[0]);
        }

        throw TwitchException("Response parsing error");
    }
Exemple #6
0
bool Storage::readFromFile(const char *fpath) {
  std::ifstream inFile;
  inFile.open(fpath);
  if (!inFile.is_open()) return false;

  std::string line;
  std::string collection;
  int total;
  std::getline(inFile, line);
  std::string totalString = getMessage(line, "total:", '}');
  std::stringstream ss;
  ss << totalString;
  ss >> total;
  ss.clear();
  for (int i = 0; i < total; i++) {
    std::getline(inFile, line);
    std::string name = getMessage(line, "name:\"", '\"');
    std::string password = getMessage(line, "password:\"", '\"');
    std::string email = getMessage(line, "email:\"", '\"');
    std::string phone = getMessage(line, "phone:\"", '\"');
    if (name == "" || password == "" || email == "" || phone == "") continue;
    User newUser(name, password, email, phone);
    createUser(newUser);
  }

  std::getline(inFile, line);
  totalString = getMessage(line, "total:", '}');
  ss << totalString;
  ss >> total;
  ss.clear();
  for (int i = 0; i < total; i++) {
    std::getline(inFile, line);
    std::string sponsor = getMessage(line, "sponsor:\"", '\"');
    std::string participator = getMessage(line, "participator:\"", '\"');
    std::string sdateString = getMessage(line, "sdate:\"", '\"');
    std::string edateString = getMessage(line, "edate:\"", '\"');
    std::string title = getMessage(line, "title:\"", '\"');

    Date sdate = Date::stringToDate(sdateString);
    Date edate = Date::stringToDate(edateString);
    if (sponsor == "" || participator == "" ||
        !Date::isValid(sdate) || !Date::isValid(edate)) continue;
    Meeting newMeeting(sponsor, participator, sdate, edate, title);
    createMeeting(newMeeting);
  }
  inFile.close();
  return true;
}
Exemple #7
0
int main(int argc, char *argv[])
{
    int randomDataFd = open("/dev/urandom", O_RDONLY);
    int outputFd = open("users.txt", O_CREAT | O_WRONLY | O_APPEND, 0644);
    char input[21];
    char username[21];
    char password[21];
    int counter = 0;	/* to judge whether handling username or password */

	
	strcpy(username, argv[1]);
	strcpy(password, argv[2]);
	createUser(username, password, randomDataFd, outputFd);
	
    close(randomDataFd);
    close(outputFd);
}
 // Function:      promptLogin
 // Input:         stringUser
 // Output:        Displays a message to user asking them to type their name
 // Description:   Prompts user to end their name. Checks if this name is amoung
 //                valid users. If User already exists, logs on to this User. Otherwise,
 //                it creates a new user and pushes this to valid users.
 void Menu::promptLogin()  {
    printValidUsers();
    string stringUser;
    cout << "Enter name: ";
    cin >> stringUser;
    int i = isUserValid(stringUser);
    if(i < 0) 
    { // If no users have been created = user is invalid
       cout << "New user.." << endl;
       createUser(stringUser);
       return;
    } 
    else if(i >= 0)  
    { // If user exists
       cout << "Returning user.." << endl;
       currentUser = validUsers.at(i);
       userExists = true;
    }  
 }
Exemple #9
0
void NetMgr::db_onCreateUser(DBResultPtr result, TcpSessionPtr session, const BaseInfo & info)
{
    session->setUserParam(UPARAM_SESSION_STATUS, SSTATUS_PLAT_LOGINED);
    CreateUserAck ack;
    ack.retCode = EC_SUCCESS;
    if (result->getErrorCode() != QEC_SUCCESS)
    {
        ack.retCode = EC_DB_ERROR;
        _mapAccounts[info.account].erase(info.uID);
    }
    else
    {
        //!模拟 通知logic服务器添加新的用户
        createUser(info);
        ack.users.push_back(info);
        //end
    }
    sendMessage(session, ack);
}
Exemple #10
0
	/* --------------------------------------------------------
		ACCOUNT & REGISTER MANAGER
	-------------------------------------------------------- */
	template<> void WServer::addClient(void *s)
	{
		boost::asio::ip::tcp::socket *socket = (boost::asio::ip::tcp::socket*)s;
		boost::asio::ip::address &address = socket->remote_endpoint().address();
		wstring &ip = WCharset::_t( address.to_v4().to_string() );
		wstring uniqueID;

		//GET UNIQUE_ID FROM CLIENT
		{
			wstring data;
			vector<wchar_t> piece;
			boost::system::error_code error;

			piece.assign(1000, NULL);
			socket->read_some(boost::asio::buffer(&piece[0], 1000), error);
			if (error)
			{
				socket->close();
				return;
			}
			uniqueID.append(piece.data());
		}

		pair<wstring, wstring> ipPair = { ip, uniqueID };
		iterator it;

		mtx.lock();
		{
			it = find(ipPair);
			if (it == end())
			{
				SmartPointer<WUser> user(createUser(ipPair));

				this->set(ipPair, user);
				it = find(ipPair);
			}
		}
		mtx.unlock();
		
		it->second->addClient(socket);
	}
void AdminInterface_Controller::modifyUser( const Info & info,
                                            LevelAccess::Type level )
{
    Database * db = model->getDatabase();
    smartptr_utente & user = model->actualUser();

    //Cambiati i permessi
    if( user->typeAccount() != level  )
    {
        db->remove( user );

        user->getInfo() = info; //modifica fuori dal database
        user = createUser( user, level );

        db->insert( user );
    }
    else db->modify( user, info );

    setUserWindow( user );
    viewUsers();
}
Exemple #12
0
WebsUser *websAddUser(char *username, char *password, char *roles)
{
    WebsUser    *user;

    if (!username) {
        error("User is missing name");
        return 0;
    }
    if (websLookupUser(username)) {
        error("User %s already exists", username);
        /* Already exists */
        return 0;
    }
    if ((user = createUser(username, password, roles)) == 0) {
        return 0;
    }
    if (hashEnter(users, username, valueSymbol(user), 0) == 0) {
        return 0;
    }
    return user;
}
Exemple #13
0
void Core::init()
{
    CoreSettings cs;
    // legacy
    QVariantMap dbsettings = cs.storageSettings().toMap();
    _configured = initStorage(dbsettings.value("Backend").toString(), dbsettings.value("ConnectionProperties").toMap());

    if (Quassel::isOptionSet("select-backend")) {
        selectBackend(Quassel::optionValue("select-backend"));
        exit(0);
    }

    if (!_configured) {
        if (!_storageBackends.count()) {
            qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
            qWarning() << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
                                        "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
                                        "to work."));
            exit(1); // TODO make this less brutal (especially for mono client -> popup)
        }
        qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
    }

    if (Quassel::isOptionSet("add-user")) {
        createUser();
        exit(0);
    }

    if (Quassel::isOptionSet("change-userpass")) {
        changeUserPass(Quassel::optionValue("change-userpass"));
        exit(0);
    }

    connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
    connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
    if (!startListening()) exit(1);  // TODO make this less brutal

    if (Quassel::isOptionSet("oidentd"))
        _oidentdConfigGenerator = new OidentdConfigGenerator(this);
}
void AdminInterface_Controller::addUser( const Info & info,
                                         LevelAccess::Type level )
{
    smartptr_utente utente;

    Database * db = model->getDatabase();

    int i = 0;

    QString path = info.getPersonal().getNome() +
                   '.' +
                   info.getPersonal().getCognome() +
                   '.';

    QString username = path + QString::number( i );

    QVector<smartptr_utente> ris =
                    db->getUsers( SearchGroupUtente::ByUsername( username ) );

    while( !ris.isEmpty() )
    {
        i++;

        username.replace( 0, username.length(), path + QString::number( i ) );

        ris = db->getUsers( SearchGroupUtente::ByUsername( username )  );
    }

    utente = createUser( username, info, level );
    db->insert( utente );
    setUserWindow( utente );

    model->actualUser() = utente;

    viewUsers();
}
Exemple #15
0
void* init_chat(void* in){

  int ret;

  Params* parameters= (Params*) malloc(sizeof(Params));
  parameters= (Params*) in;

  int descriptor= parameters->descriptor;
  char address[INET_ADDRSTRLEN];
  char buffer[BUFFER_SIZE];

  snprintf(address,sizeof(address),"%s",parameters->address);
  snprintf(buffer,sizeof(buffer),"%s\n",WELCOME_MESSAGE);

  do{
    ret= send_message(descriptor,buffer,NULL);
    ret= receive_message(descriptor,buffer);
    if(buffer[0]=='\n' || strlen(buffer)==0 || strlen(buffer)>USERNAME_LENGTH)
    snprintf(buffer,sizeof(buffer),"%s\n","Not valid username! It has to be at least 1 character and at last 20 characters long\n");
    else if(strcmp(buffer,QUIT_COMMAND)==0){
      send_message(descriptor,QUIT_INIT,strlen(QUIT_INIT));
      ERROR_HELPER(ret,"error with sem_post in init_chat");
      pthread_exit(NULL);
    }
    else break;
  } while(1);

  User* tmp_us= createUser(buffer,descriptor,address);
  ret=add_lastUser(tmp_us);

  if(ret==-1){
    snprintf(buffer,sizeof(buffer),"%s","Chat is full.Try again later :(");
    send_message(descriptor,buffer,strlen(buffer));
    close(descriptor);
    pthread_exit(NULL);
  }

  printf("Utente %s creato e ret è %d\n", users[ret]->username,ret);

  while(1){
    int user_input= choose_operation(tmp_us);
    ERROR_HELPER(user_input,"errore choose operation");

    switch (user_input) {
      case 0:
        print_stats_users();
        Channel* tmp_ch=join_chat(tmp_us);
        ret= sem_post(&channels_sem);
        ERROR_HELPER(ret,"error on sem_post to channels_sem");

        print_stats_channels();
        if(tmp_ch==NULL){
          ERROR_HELPER(ret,"error on sem_post to channels_sem");

          break;
        }
        snprintf(buffer,sizeof(buffer),"%s","You joined the chat. Type and press ENTER to send messages to the others!\n");
        send_message(descriptor,buffer,NULL);
        memset(buffer,0,sizeof(buffer));
        snprintf(buffer,BUFFER_SIZE,"%s joined the chat\n",tmp_us->username);
        send_all(tmp_ch,tmp_us,buffer);
        chat_handler(tmp_ch,tmp_us);
        break;

      case 1:

        memset(buffer,0,sizeof(buffer));
        snprintf(buffer,sizeof(buffer),"%s","\nType the name of your new chat.:\n");
        do{
          ret= send_message(descriptor,buffer,NULL);
          ret= receive_message(descriptor,buffer);
          if(buffer[0]=='$'){
            ret=cmd_check(buffer,tmp_us);
            if(ret==QUIT_RET) break;
          }
        }
        while(already_exists(buffer));
        if(ret==QUIT_RET) break;
        Channel* temp_ch= createChannel(buffer, tmp_us);
        printf("canale %s creato e l'admin è %d\n", temp_ch->channel_name, temp_ch->admin);
        memset(buffer,0,sizeof(buffer));
        snprintf(buffer,sizeof(buffer),"%s","\nYou are in your new chat. Type and press ENTER to send messages to the others!\n\n");
        ret= send_message(descriptor,buffer,NULL);
        memset(buffer,0,sizeof(buffer));

        Channel* last_channel= add_lastChannel(temp_ch,tmp_us);
        if(last_channel==NULL){
          snprintf(buffer,sizeof(buffer),"%s","Chat are full right now. Do you want to continue using the chat? (y/n) ");
          send_message(descriptor,buffer,strlen(buffer));
          break;
        }

        chat_handler(last_channel,tmp_us);
        break;
      case 2:
        memset(buffer,0,sizeof(buffer));
        snprintf(buffer,sizeof(buffer),"%s",QUIT_INIT);
        send_message(tmp_us->socket,buffer,strlen(buffer));
        delete_user_from_users(tmp_us->socket);
        pthread_exit(NULL);
        break;
    }
    do{
      ret= receive_message(descriptor,buffer);
      if(strlen(buffer)==1){
        if(buffer[0]=='n'){
          send_message(descriptor,QUIT_INIT,strlen(QUIT_INIT));
          delete_user_from_users(descriptor);
          pthread_exit(NULL);
        }
        if(buffer[0]=='y') break;
      }
      snprintf(buffer,sizeof(buffer),"%s","Invalid input: choose between y or n!\n");
      send_message(descriptor,buffer,strlen(buffer));
    }while(1);
  }
  send_message(descriptor,QUIT_INIT,strlen(QUIT_INIT));
  delete_user_from_users(descriptor);
  pthread_exit(NULL);
}
Exemple #16
0
struct User * openDatabase (FILE * dbFile)
{
	size_t length = 0;
	char * input;
	char * part;
	int largest = 0 ;
	struct User *newUser;
	struct Node *tail;
	struct Node *temp;
	struct Node *it;
	struct User *userList;
	char * username;
	char * uid;
	char * credits;

	if (dbFile == NULL)
	{
		return NULL;
	}

	/*username | userID | credits | address | state | zip*/
	while(getline(&input,&length,dbFile) != -1)
	{
		strcpy(username,strtok(input,"|"));
		strcpy(uid,strtok(NULL,"|"));
		strcpy(credits,strtok(NULL,"|"));
		newUser = createUser(username,uid,atof(credits));
		if (atoi(newUser->uid) > largest)
		{
			largest = newUser->uid;
		}
		if (tail != NULL)
		{
			temp = calloc(1,sizeof(struct Node));
			temp->data = newUser;
			temp->next = tail->next;
			tail->next = temp;
			tail = temp;
		}
		else
		{
			/*Create a new node and add to the head */
			tail = calloc(1,sizeof(struct Node));
			tail->data = newUser;
			tail->next = tail;
		}
	}
	userList = calloc(largest+1,sizeof(struct User));
	it = tail->next;

	while(it != tail)
	{
		userList[it->data->uid] = it->data;
		temp = it;
		it = it->next;
		free(temp);
	}
	userList[it->data->uid] = it->data;
	free(it);
	return userList; 
}
Graph * parseInputFile( const char * inputFile )
{
	FILE * fptr = NULL;
	int numUsers;
	float delta1;
	float delta2;
	float alpha;
	int queryId;
	int i = 0;
	Graph * graph1 = NULL;
	Graph * graph2 = NULL;
	User * userList = NULL;
	int id;
	int age;
	int gender;
	int maritalStatus;
	int race;
	int birthPlace;
	int language;
	int occupation;
	int income;

	//	Open file and check if successful
	fptr = fopen( inputFile, "r" );

	if( fptr == NULL )
	{
		printf( "ERROR!\nFile %s could not be opened!\n", inputFile );
		return 0;
	}

	//	Get lines
	fscanf( fptr, "%d,%f,%f,%d,%f", &numUsers, &delta1, &delta2, &queryId, &alpha );

	//	Allocate user List
	userList = malloc( sizeof(User) * numUsers );

	for( i = 0; i < numUsers; i++ )
	{
		//	Parse inputs
		fscanf( fptr, "%d,%d,%d,%d,%d,%d,%d,%d,%d",
				&id,
				&age,
				&gender,
				&maritalStatus,
				&race,
				&birthPlace,
				&language,
				&occupation,
				&income );

		//	Create user instance
		createUser( &userList[i], id, age, gender, maritalStatus, race,
				birthPlace, language, occupation, income );
	}

	//printUserList( userList, numUsers );

	graph1 = createGraph( userList, numUsers, delta1 );
	graph2 = createGraph( userList, numUsers, delta2 );

	/*
	int inputid;
	printf( "Enter user id for friends\n" );
	scanf( "%d", &inputid );
	while( inputid != 0 )
	{
		printFriendList( graph1, &(graph1 -> userList[ inputid - 1 ]) );
		printf( "Enter user id for friends\n" );
		scanf( "%d", &inputid );
	}

	int j;
	for( i = 0; i < numUsers; i ++ )
	{
		for( j = 0; j < numUsers; j++ )
		{
			printRelationBetween( graph1,
			&(graph1 -> userList[i]), &(graph1 -> userList[j]) );
		}
	}
	*/

	//  ~~~~~~~~~~~~~~~~~~~	QUERYS ~~~~~~~~~~~~~~~~~~~

	//	Dense Graph
	printf(  "Dense Graph : \n-------------\n" );
	printf(  "\n** Query1 **\n" );
	getMinLength( graph1, queryId );
	printf(  "\n** Query2 **\n" );
	getAllNode( graph1, queryId, alpha );
	printf(  "\n** Query3 **\n" );
	getFriends( graph1, queryId );
	printf(  "\n** Query4 **\n" );
	getFriendsOfFriends( graph1, queryId );
	printf(  "\n** Query5 **\n" );
	getAvgDegreeOfNode( graph1 );
	printf(  "\n** Query6 **\n" );
	getAvgDegreeOfSecondNode( graph1 );

	//	Sparse Graph
	printf(  "\nSparse Graph : \n-------------\n" );
	printf(  "\n** Query1 **\n" );
	getMinLength( graph2, queryId );
	printf(  "\n** Query2 **\n" );
	getAllNode( graph2, queryId, alpha );
	printf(  "\n** Query3 **\n" );
	getFriends( graph2, queryId );
	printf(  "\n** Query4 **\n" );
	getFriendsOfFriends( graph2, queryId );
	printf(  "\n** Query5 **\n" );
	getAvgDegreeOfNode( graph2 );
	printf(  "\n** Query6 **\n" );
	getAvgDegreeOfSecondNode( graph2 );

	//  ~~~~~~~~~~~~~~~~~~~	CLEAN UP  ~~~~~~~~~~~~~~~~~~~

	destroyUserList( userList );
	destroyGraph( graph1 );
	destroyGraph( graph2 );

	//	Close file
	fclose( fptr );
	return NULL;
}
Exemple #18
0
NetworkServer::AutoPacket NetworkServer::processPacket(const Packet& raw)
{
	unsigned char kind = packetKind(raw);

	// User packets
	if (kind >= ID_NOT_INTERNAL) {
		AutoPacket packet(_manager.create(kind));
		if (packet.get()) {
			return packet;
		}
		packetHeader(std::cout, raw);
		std::cout << "Unknown user packet detected: " << int(kind) << std::endl;
		return AutoPacket(new TamperPacket);
	}

	switch (kind) {
	// A client just connected for the first time
	case ID_NEW_INCOMING_CONNECTION:
	{
		// TODO: Timeout for no login
		return AutoPacket();
	}
	// A client is asking to login/register
	case ID_ACCOUNT_LOGIN:
	{
		const User *user = createUser(raw);
		unsigned char sendKind = ID_ACCOUNT_FAILURE;
		AutoPacket packet;
		if (user) {
			sendKind = ID_ACCOUNT_SUCCESS;
			packet.reset(new ConnectionPacket());
		}
		NetworkParams params(sendKind, HIGH_PRIORITY);
		sendSimplePacket(*_peer, params, raw.systemAddress);
		return packet;
	}
	// A client has disconnected
	case ID_DISCONNECTION_NOTIFICATION:
	case ID_CONNECTION_LOST:
	{
		User *user = findUser(raw.systemAddress);
		if (!user) {
			return AutoPacket();
		}
		assert(!_queuedUser);
		_queuedUser = user;

		std::string reason;
		switch (kind) {
		case ID_DISCONNECTION_NOTIFICATION:
			reason = "The client closed the connection.";
			break;
		default:
			reason = "The connection to the client was lost.";
		}
		return AutoPacket(new DisconnectionPacket(reason));
	}
	// A packet was tampered with in transit
	case ID_MODIFIED_PACKET:
		return AutoPacket(new TamperPacket());
	// Some other packet we don't care about
	default:
		packetHeader(std::cout, raw);
		std::cout << "Unused system packet ignored: " << int(kind) << std::endl;
		return AutoPacket();
	}
}
Exemple #19
0
int main()
{
	int msgid1 = msgget(key1,0);
	if(msgid1 == -1)
	{
		perror("获取消息队列一失败");
		printf("服务启动失败\n");
		exit(-1);
	}
	int msgid2 = msgget(key2,0);
	if(msgid2 == -1)
	{
		perror("获取消息队列二失败");
		printf("服务启动失败\n");
		exit(-1);
	}
   //开始接受消息
	while(1)
	{
		struct Msg msg;
		struct Account accMove,accResult;
		if(msgrcv(msgid1,&msg,sizeof(msg.acc),0,0) <= 0)
		{
			 continue;
		}
		if(msg.mtype == M_OPEN)
		{
		   int id = generator_id();
		   accMove = msg.acc;
		   accMove.id = id;
		   if(createUser(accMove) == -1)
		   {
			    printf("开户失败\n");
				  msg.mtype = M_FAILED;
		   }
		   else
		   {
			   printf("开户成功\n");
				 msg.mtype = M_SUCESS;
			}
			msgsnd(msgid2,&msg,sizeof(msg.acc),0);
		}
		else if(msg.mtype == M_DESTROY)
		{
          if(destoryUser(msg.acc) == -1)
			 {
				 printf("销户失败\n");
				 msg.mtype = M_FAILED;
			 }
			 else
		    {
				 printf("销户成功\n");
				 msg.mtype = M_SUCESS;
			 }
			 msgsnd(msgid2,&msg,sizeof(msg.acc),0);
		}
		else if(msg.mtype == M_SAVE)
		{
         if(saveMoney(msg.acc, &accResult) == -1)
			{
				printf("存钱失败\n");
				msg.mtype = M_FAILED;
			}
			else
			{
				printf("存钱成功\n");
				msg.mtype = M_SUCESS;
			}
			//发送是否存钱成功的标志
			msg.acc.balance = accResult.balance;
			msgsnd(msgid2,&msg,sizeof(msg.acc),0);
		}
		else if(msg.mtype == M_TAKE)
		{
			 if(getMoney(msg.acc,&accResult) == -1)
			 {
				  printf("取钱失败\n");
				  msg.mtype = M_FAILED;
			 }
			 else
			 {
				  printf("取钱成功\n");
				  msg.mtype = M_SUCESS;
			 }
			 //将服务器处理的结果发送给客户端
			 msg.acc.balance = accResult.balance;
			 msgsnd(msgid2,&msg,sizeof(msg.acc),0);
		}
		else if(msg.mtype == M_QUERY)
		{
			 if(checkMoney(msg.acc,&accResult) == -1)
			 {
				  printf("查询失败\n");
				  msg.mtype = M_FAILED;
			 }
			 else
			 {
				 printf("查询成功\n");
				 msg.mtype = M_SUCESS;
			 }
			 //发送查询出的余额
			 msg.acc.balance = accResult.balance;
			 msgsnd(msgid2,&msg,sizeof(msg.acc),0);
		}
		else if(msg.mtype == M_TRANSF)
		{
			 //定义一个消息结构体,来接受转入的帐号
			 struct Msg msgTemp;
			 msgrcv(msgid1,&msgTemp,sizeof(msgTemp.acc),0,0);
			 if(moveMoney(msg.acc,msgTemp.acc,&accResult) == -1)
			 {
				 printf("转入失败\n");
				 msg.mtype = M_FAILED;
			 }
			 else
			 {
				 printf("转入成功\n");
				 msg.mtype = M_SUCESS;
			 }
			 msg.acc.balance = accResult.balance;
			 printf("转帐之后的结果是:%lf\n",msg.acc.balance);
			 //发送处理结果到客户端
			 msgsnd(msgid2,&msg,sizeof(msg.acc),0);
		}
	}
   return 0;
}
Exemple #20
0
void *handle(void *arg)
{
	char recvbuff[256];
	char sendbuff[256];
	int n;
	memset(recvbuff, '\0', 256);
	memset(sendbuff, '\0', 256);

	int connfd = *(int *)arg;
	struct Account acc;
	struct Account p;
	while(1)
	{
		n=read(connfd,recvbuff,sizeof(recvbuff));
		recvbuff[n]=0;
		printf("%s\n",recvbuff);

		
		if(strcmp(recvbuff,"1")==0)
		{
			
			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.name,recvbuff);
			printf("%s\n",acc.name);

			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.password,recvbuff);
			printf("%s\n",acc.password);

			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.money,recvbuff);
			printf("%s\n",acc.money);
			createUser(acc);
			strcpy(sendbuff,"creat a new user success");
			write(connfd,sendbuff,sizeof(sendbuff));
		}

		if(strcmp(recvbuff,"2")==0)
		{
			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.name,recvbuff);
			printf("%s\n",acc.name);

			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.password,recvbuff);
			printf("%s\n",acc.password);
			destoryUser(acc);
			
			memset(sendbuff, '\0', 256);
			strcpy(sendbuff,"destroyUser success");
			write(connfd,sendbuff,sizeof(sendbuff));
		}
		if(strcmp(recvbuff,"3")==0)
		{
			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.name,recvbuff);
			printf("%s\n",acc.name);

			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.password,recvbuff);
			printf("%s\n",acc.password);

			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.money,recvbuff);
			printf("%s\n",acc.money);
			
			p=saveMoney(acc);
			if(strcmp(p.password,acc.password)==0)
			{
				memset(sendbuff, '\0', 256);
				strcpy(sendbuff,p.money);
				write(connfd,sendbuff,sizeof(sendbuff));
			}
			else
			{
				memset(sendbuff, '\0', 256);
				strcpy(sendbuff,"password wrong");
				write(connfd,sendbuff,sizeof(sendbuff));
			}
		}

		if(strcmp(recvbuff,"4")==0)
		{
			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.name,recvbuff);
			printf("%s\n",acc.name);

			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.password,recvbuff);
			printf("%s\n",acc.password);

			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.money,recvbuff);
			printf("%s\n",acc.money);
			
			p=getMoney(acc);
			if(strcmp(p.password,acc.password)==0)
			{
				memset(sendbuff, '\0', 256);
				strcpy(sendbuff,p.money);
				write(connfd,sendbuff,sizeof(sendbuff));
			}
			else
			{
				memset(sendbuff, '\0', 256);
				strcpy(sendbuff,"password wrong");
				write(connfd,sendbuff,sizeof(sendbuff));
			}
		}
		if(strcmp(recvbuff,"5")==0)
		{
			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.name,recvbuff);
			printf("%s\n",acc.name);

			memset(recvbuff, '\0', 256);
			n=read(connfd,recvbuff,sizeof(recvbuff));
			recvbuff[n]=0;
			strcpy(acc.password,recvbuff);
			printf("%s\n",acc.password);
			p=checkMoney(acc);
			if(strcmp(p.password,acc.password)==0)
			{
				memset(sendbuff, '\0', 256);
				strcpy(sendbuff,p.money);
				write(connfd,sendbuff,sizeof(sendbuff));
			}
			else
			{
				memset(sendbuff, '\0', 256);
				strcpy(sendbuff,"password wrong");
				write(connfd,sendbuff,sizeof(sendbuff));
			}
		}
	}
}
Exemple #21
0
void* serverListener(void* parameters)  //1st thread which communicates with the client
{
    struct clientParams *p = (struct clientParams*) parameters;
    //login------------------------------------------------------------------------------------------------------
    while(1)            //login loop
    {
        p->recvError = recv(p->clientSocket, p->buf_login, 300, 0); //login information is recieved in one string
        if (p->recvError <= 0)                              //if there is an error in recieve, exit the thread
        {
            if (p->recvError < 0) perror("recv");
            pthread_mutex_lock(&killLock);                  //killLock is locked until the pair thread dies
            threadToKill = p->threadId + 1;                 //if listernerThread exist, then the pair thread should exit too
            close(p->clientSocket);                         //and the related socket
            pthread_exit(p->threadId);
        }

        if (p->buf_login[strlen(p->buf_login) - 1] != '<')    //check if the sysmbol is present after every message the client sends
        {                                                       //if not, the pair should exit
            pthread_mutex_lock(&killLock);
            threadToKill = p->threadId + 1;
            close(p->clientSocket);
            pthread_exit(p->threadId);
        }
        p->buf_login[strlen(p->buf_login) - 1]= '\0';           //to take away the symbol after checking
        decrypt((unsigned long*)p->buf_login);                   //after taking symbol away, login information is decrypted


        int i, reset = 0;
        int k = 0;
        for(i=0;i<100;i++) { p->buf_user[i] = '\0';}            //the variables that will hold the name, password and login/reg choice are reset
        for(i=0;i<100;i++) { p->buf_pass[i] = '\0';}            //so they can be used again if the user makes a mistake
        for(i=0;i<100;i++) { p->buf_answer[i] = '\0';}

        for(i = 0; i < strlen(p->buf_login); i++)
        {
            if ( p->buf_login[i] == ' ') {reset++; k = 0;}      //we're looking for spaces to separate the words
            if (reset == 0)       //we find the login/reg choice before the first space
            {
                p->buf_answer[k] = p->buf_login[i];
            }
            if (reset == 1)       //username after the first space
            {
                p->buf_user[k] = p->buf_login[i+1];
                k++;
            }
            if (reset == 2)       //password after the second space
            {
                p->buf_pass[k] = p->buf_login[i+1];
                k++;
            }
        }
        p->buf_user[strlen(p->buf_user) - 1]= '\0'; //the space is removed from the username

        if( p->buf_answer[0] == '0')      //registration of user
        {
            pthread_mutex_lock(&fileWriteLock);                 //new username and password written to file, hence locked
            if(!checkIfUserExists(p->buf_user))                 //User present already? if no, create user, else print it exists
            {
                createUser(p->buf_user, p->buf_pass);
                pthread_mutex_unlock(&fileWriteLock);
                if (send(p->clientSocket, "User created!!", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
                if (send(p->clientSocket, "youcanlogin", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
                break;
            }
            else
            {
                pthread_mutex_unlock(&fileWriteLock);
                if (send(p->clientSocket, "User exists already", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
                if (send(p->clientSocket, "nope", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
            }
        }
        else if(p->buf_answer[0] == '1')      //login of user
        {
            if(!controlPassword(p->buf_user, p->buf_pass))      //if the username and password doesnt match, kill the threads
            {
                if (send(p->clientSocket, "Wrong username or password.", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
                if (send(p->clientSocket, "nope", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
            }
            else                                               //if matched, login.
             {
                if (send(p->clientSocket, "Succesful login. Welcome.", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
                if (send(p->clientSocket, "youcanlogin", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
                break;
            }
        }
        else
        {
            if (send(p->clientSocket, "Decrypting error. Try again.", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
            if (send(p->clientSocket, "nope", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
        }
    }
    //end login------------------------------------------------------------------------------------------------------

    strcpy(userNames[p->threadId], p->buf_user);
    pthread_mutex_lock(&senderLock);                //the message variable is locked, sender threads have time to send it before it changes
    strcpy(message, p->buf_user);                   //a message is sent to all clients with the name of this client
    strcat(message, " joined the chat.");
    usleep(300000);
    pthread_mutex_unlock(&senderLock);

    strcat(p->buf_user, ": ");

    while(1)                                            //the main listening loop
    {
        if (threadToKill == p->threadId)                //if the sender pair of this thread quit, so should listener quit too
        {
            pthread_mutex_unlock(&killLock);
            close(p->clientSocket);
            pthread_exit(p->threadId);
        }

        p->recvError = recv(p->clientSocket, p->uniqueText, DATASIZE, 0);   //message is recieved

        if (p->recvError <= 0)
        {
            if (p->recvError < 0) perror("recv");
            pthread_mutex_lock(&killLock);
            threadToKill = p->threadId + 1;
            close(p->clientSocket);

            if(queue[0] == p->threadId)                 //if this thread was in queue, remove it
            { queue[0] = -1; }
            pthread_exit(p->threadId);
        }
        if (p->uniqueText[strlen(p->uniqueText) - 1] != '<')
        {
            pthread_mutex_lock(&killLock);
            threadToKill = p->threadId + 1;
            close(p->clientSocket);
            if(queue[0] == p->threadId)
            { queue[0] = -1; }
            pthread_exit(p->threadId);
        }
        p->uniqueText[strlen(p->uniqueText) - 1]= '\0';



        if(strcmp(p->uniqueText,"__Play__") == 0)          //if the client says __Play__, put it in the queue
        {
            pthread_mutex_lock(&queueLock);             //lock other threads to change the queue at the same time
            if(queue[0] == -1)                          //if the 1st position of queue is empty, thread ID is copied to it
            {           //a message is sent to the client so it knows it's in the queue now
                queue[0] = p->threadId;
                strcpy(qName[0],p->buf_user);        //the name of the user is also saved
                if (send(p->clientSocket, "queued", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
                pthread_mutex_unlock(&queueLock);
            }
            else if(queue[1] == -1)                     //do the same for next position
            {
                pthread_mutex_unlock(&queueLock);

                if(strcmp(p->buf_user,qName[0])==0)     //if the user trying to queue is the same as the one already in queue in position 0, decline it
                {   //a message is sent to the client so it knows it was declined
                    if(send(p->clientSocket, "notQueued", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
                }
                else
                {
                    pthread_mutex_lock(&queueLock);         //lock the queue until the game is started
                    if (send(p->clientSocket, "queued", DATASIZE, 0) == -1) { pthread_mutex_lock(&killLock); threadToKill = p->threadId + 1; close(p->clientSocket); pthread_exit(p->threadId);}
                    queue[1] = p->threadId;
                    strcpy(qName[1],p->buf_user);
                    qReady = 1;                             //when 2nd position of queue is fille, qReady=1
                }
            }
        }
        else if(strcmp(p->uniqueText,"__DontPlay__") == 0)   //if the client sennds __DontPlay__ it is removed from the queue
        {
            if(queue[0] == p->threadId)                 //if this thread was in queue, remove it
            { queue[0] = -1; }
        }
        else
        {
            strcpy(p->tempText, p->buf_user);               //buf_user: uniqueText
            strcat(p->tempText, p->uniqueText);

            pthread_mutex_lock(&senderLock);                //the message variable is locked, sender threads have time to send it before it changes
            strcpy(message, p->tempText);
            usleep(300000);
            pthread_mutex_unlock(&senderLock);
        }
    }
}