Пример #1
0
void MainWindow::runServer()
{
	this->setWindowTitle("Player1");
	server = new QTcpServer(this);
	if(!server->listen(QHostAddress::Any, 5555))
	{
		ui->statusBar->showMessage("Unable to start game server.");
		return;
	}
	ui->connectBox->setEnabled(FALSE);
	ui->statusBar->showMessage("Game Server running. Waiting for other player...");
	ui->gameBox->setEnabled(TRUE);
	ui->playButton->setEnabled(FALSE);
	isserver = TRUE;
	connect(server, SIGNAL(newConnection()), this, SLOT(connectToClient()));
}
Пример #2
0
void *sendOneUpdateToAllClient(void *msg)
{
	clntData_t *reqMsg = NULL;
	reqMsg = (clntData_t*)msg;
	if(reqMsg == NULL)
	{
		LOG_ERROR("Msg is NULL");
		return;
	}
	char i =0;
	int sockFd = 0;
	CLIENT_DB *cdb = getClientDbInstance();
	if(!cdb)
	{
		LOG_ERROR("Error in client db instance");
		return;
	}	
	for(i=0; i<MAX_CLIENT; i++)
	{
		// skip current client and unregistered client
		if(cdb->clientState[i] == clnt_unregister_state)
			continue;
		if((i == reqMsg->header.clntId) && (reqMsg->header.msgId != client_currentPlaying_m))
			continue;

		if(connectToClient(i, &sockFd) != G_OK)
		{
			LOG_ERROR("Unable to connect with client for sending update");
			cdb->deregisterClient(cdb,i);
			continue;
		}
		if(sendOneUpdate(reqMsg, sockFd) != G_OK)
		{
			LOG_ERROR("Sending update all fail");
		}
		closeSocket(sockFd);
	}
	if(reqMsg->payLoad != NULL)
		free(reqMsg->payLoad);

	free(reqMsg);
}
Пример #3
0
//Select transport based on profile and opts and set default GUID
int MF_BaseSocketManager::openRequest(MF_APIOpen *event){
	MF_Log::mf_log(MF_DEBUG, "MF_BaseSocketManager:open request analyzing request profile=%s guid=%d", event->getProfile(), event->getSrcGUID());
	if(!strcmp("basic", event->getProfile())){
		type = 1;
	} else{
		MF_Log::mf_log(MF_ERROR, "MF_BaseSocketManager:openRequest wrong profile request %s", event->getProfile());
		openReplyError(STACK_ACTION_FAILURE);
		return -1;
	}

	//Create transport
	if (transSetting.isReliabTrans) {
		trnsp = new MF_ReliabTransport(ID, &recvBuffer, &sendBuffer, _system);
		((MF_ReliabTransport*)(trnsp))->setTransSetting(transSetting);
	} else {
		trnsp = new MF_BasicTransport(ID, &recvBuffer, &sendBuffer, _system);
	}
	trnsp->setMyGUID(event->getSrcGUID());

	_system->getSocketTable()->addManager(this);
	if(event->getSrcGUID()==0){
		MF_Log::mf_log(MF_DEBUG, "MF_BaseSocketManager:openRequest using device default srcGUID");
		_system->getSocketTable()->addGUID(event->getUID(), _system->getRouter()->getDefaultGUID());
		GUIDs.push_back(_system->getRouter()->getDefaultGUID());
	}
	else{
		_system->getSocketTable()->addGUID(event->getUID(), event->getSrcGUID());
		_system->getRouter()->addGUID(event->getSrcGUID());
		GUIDs.push_back(event->getSrcGUID());
	}
	_system->getSocketTable()->addTID(ID, ID);

	startAliveTimer();

	MF_Log::mf_log(MF_DEBUG, "MF_BaseSocketManager:openRequest opened new socket with ID=%u default srcGUID=%d", ID, event->getSrcGUID());
	open = true;
	openReplySuccess();
	connectToClient();
	return 0;
}
Пример #4
0
static void sendDeleteOneToClient(char clientId, u32 m_token)
{
	int sockFd = 0;
	clntData_t *data = NULL;
	CLIENT_DB *cdb = getClientDbInstance();
	data = createClientMsg(clientId,m_token,client_delete_req_m);
	if(connectToClient(clientId,&sockFd) != G_OK)
	{
		LOG_ERROR("Unable to connect to client");
		free(data);
		return;
	}

	if(sendOneUpdate(data,sockFd) != G_OK)
	{
		LOG_ERROR("Unable to send delete message to client");
		free(data);
		closeSocket(sockFd);
	}
	free(data);
	closeSocket(sockFd);
}
Пример #5
0
void SaveConfig::go()
{
    FdPtr_t sockfd = connectToClient(*this);    //< create a connection
    Marshall marshall;        //< create a marshaller
    marshall.setFd(*sockfd);  //< tell the marshaller the socket to use
    handshake(marshall);      //< perform handshake protocol

    // send the message
    messages::SaveConfig* msg =
        new messages::SaveConfig();
    // fill the message
    msg->set_filename(fileName.getValue());

    // send the message to the backend
    marshall.writeMsg(msg);

    // wait for the reply
    RefPtr<AutoMessage> reply = marshall.read();

    // if the backend replied with a message we weren't expecting then
    // print an error
    if( reply->type != MSG_UI_REPLY )
    {
            std::cerr << "Unexpected reply of type: "
              << messageIdToString( reply->type )
              << "\n";
    }
    // otherwise print the result of the operation
    else
    {
    messages::UserInterfaceReply* msg =
            static_cast<messages::UserInterfaceReply*>(reply->msg);
       std::cout << "Server reply: "
              << "\n    ok? : " << (msg->ok() ? "YES" : "NO")
              << "\nmessage : " << msg->msg()
              << "\n";
    }
}
Пример #6
0
void * sendAllUpdateToClient(void *data)
{
	int i = 0, j = 0;
	char isClientConnected = 0;
	int sockFd = 0;
	RESULT sendResult = G_FAIL;
	char clientId = *((char*)data);
	clntData_t clntData;
	CLIENT_DB *cdb = getClientDbInstance();
	if(!cdb)
	{
		LOG_ERROR("Error in client db instance");
		return;
	}
	if(clientId >= MAX_CLIENT)
	{
		LOG_ERROR("Invalid client Id, clntId =%d",clientId);
		return NULL;
	}
	if(cdb->clientState[clientId] == clnt_unregister_state)
	{
		LOG_ERROR("Client is already de registered, clntId =%d",clientId);
		return NULL;
	}
	PLAYLIST *pl = cdb->playList;
	// LOCK the playlist
	pthread_mutex_lock(&pl->playListLock);
	if(pl->playListSize <= 0)
	{
		LOG_MSG("Playlist is empty, nothing to update");
		pthread_mutex_unlock(&pl->playListLock);
		return NULL;
	}
	LIST_NODE *tempNode = NULL;
	for(i=0; i<MAX_CLIENT; i++)
	{
		// skip current client and unregistered client
		if((cdb->clientState[clientId] == clnt_unregister_state) || (i == clientId))
			continue;

		//skip client having not data
		if(pl->pList[i].totalNode == 0)
		{
			continue;
		}
		tempNode = pl->pList[i].first;
		for(j=0; j<pl->pList[i].totalNode; j++)
		{
			// create client message;
			clntData.header.clntId = clientId;
			clntData.header.msgId  = client_update_all;
			clntData.header.isLast = 0;
			clntData.header.token  = getNewToken();
			clntData.header.totalSize = 0;
			clntData.payLoad  = ((PlayListData*)(tempNode->data))->data;
			clntData.payloadSize = ((PlayListData*)(tempNode->data))->size;
			
			//if client is not connected connect with it
			if(!isClientConnected)
			{
				if(connectToClient(clientId, &sockFd) != G_OK)
				{
					LOG_ERROR("Unable to connect with client for sending update");
					break;
				}
				isClientConnected = 1;
			}
			if((sendResult = sendOneUpdate(&clntData, sockFd)) != G_OK)
			{
				LOG_ERROR("Sending update all fail");
				break;
			}
			tempNode = tempNode->next;
			clntData.payLoad = NULL;
			clntData.payloadSize = 0;
		}
		if(sendResult != G_OK)
		{
			break;
		}
	}
	if(isClientConnected)
	{
		closeSocket(sockFd);
	}
	pthread_mutex_unlock(&pl->playListLock);
	
}
Пример #7
0
int main(int argc, char *argv[]){
    
    struct sockaddr_in server;
    int new_sock, server_sock = -1;
    int addrlen;
    char command[128], buf[128];
    
    if (argc != 2) {
        (void) fprintf(stderr,"usage: %s port# \n",argv[0]);
        exit(1);
    }
    
    portnum = atoi(argv[1]);
    
    // Create a Server Socket
    if((server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
        perror("socket");
        exit(1);
    }
    
    memset((void*)&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons((u_short)atoi(argv[1]));
    
    if(bind(server_sock, (struct sockaddr *)&server, sizeof server) < 0) {
        perror("bind");
        exit(1);
    }
    
    if(listen(server_sock, SOMAXCONN) < 0) {
        perror("listen");
        exit(1);
    }
    
    
    
    //
    //
    //
    while(1){
        // Input from the keyboard
        memset(command, 0x00, sizeof command);
        
        addrlen = sizeof server;
        new_sock = accept(server_sock,
                          (struct sockaddr *)&server,
                          (socklen_t *)&addrlen);
        
        if (new_sock < 0) {
            perror("accept");
            exit(1);
        }
        
        printf("connection : Host IP %s, Port %d, socket %d\n",
               inet_ntoa(server.sin_addr), ntohs(server.sin_port), new_sock);
        
        read(new_sock, command, sizeof command);	// read user command
        printf("%s", command);
        
        if(!strncmp(command, "@quit", 5)){			// quit
            memset(buf, 0x00, sizeof(buf));
            
            strcat(buf, "@delete ");
            strcat(buf, inet_ntoa(server.sin_addr));
            strcat(buf, " ");
            strcat(buf, toArray(ntohs(server.sin_port)));
            
            struct node* delNode = find(inet_ntoa(server.sin_addr), ntohs(server.sin_port));
            int roomNum = delNode->room;
            delNode->room = 0;
            
            current = head;
            while(current != NULL){
                if(current->room == roomNum)
                    connectToClient(current->IP, toArray(current->port), buf);
                current = current->next;
            }
        }
        else if(!strncmp(command, "@exit", 5)){		// exit
            memset(buf, 0x00, sizeof(buf));
            
            strcat(buf, "@delete ");
            strcat(buf, inet_ntoa(server.sin_addr));
            strcat(buf, " ");
            strcat(buf, toArray(ntohs(server.sin_port)));
            strcat(buf, "\n");
            
            int roomNum = find(inet_ntoa(server.sin_addr), ntohs(server.sin_port))->room;
            deletes(inet_ntoa(server.sin_addr), ntohs(server.sin_port));
            if(roomNum != 0){
                current = head;
                while(current != NULL){
                    if(current->room == roomNum)
                        connectToClient(current->IP, toArray(current->port), buf);
                    current = current->next;
                }
            }
        }
        else if(!strncmp(command, "@connect", 8)){	// connect
            insertFirst(inet_ntoa(server.sin_addr), ntohs(server.sin_port), &command[9], 0);
            printf("%s is connected\n", &command[9]);
            
            if (write(new_sock, "connection ok", strlen("connection ok")) < 0) {
                perror("write");
                exit(1);
            }
        }
        else if(!strncmp(command, "@getlist", 8)){		// user & room list
            memset(buf, 0x00, sizeof(buf));
            for(int i=0; i<room_size; i++){
                if(i == 0){
                    strcat(buf, "\n==========waiting room ");
                    strcat(buf, "==========\n");
                }
                else{
                    strcat(buf, "==========room# ");
                    strcat(buf, toArray(i));
                    strcat(buf, "==========\n");
                }
                
                current = head;
                while(current != NULL){
                    if(current->room == i){
                        strcat(buf, current->IP);
                        strcat(buf, " ");
                        strcat(buf, toArray(current->port));
                        strcat(buf, " ");
                        strcat(buf, current->ID);
                        strcat(buf, "\n");
                    }
                    current = current->next;
                }
            }
            
            if (write(new_sock, buf, strlen(buf)) < 0) {
                perror("write");
                exit(1);
            }
        }
        else if(!strncmp(command, "@mkroom", 7)){	// mkroom
            room_size++;
            memset(buf, 0x00, sizeof(buf));
            strcat(buf, "room ");
            strcat(buf, toArray(room_size));
            strcat(buf, " is created\n");
            
            if (write(new_sock, buf, strlen(buf)) < 0) {
                perror("write");
                exit(1);
            }
        }
        else if(!strncmp(command, "@join", 5)){		// join
            int roomNum = atoi(&command[6]);
            
            memset(buf, 0x00, sizeof(buf));
            strcat(buf, "@add ");
            strcat(buf, inet_ntoa(server.sin_addr));
            strcat(buf, " ");
            strcat(buf, toArray(ntohs(server.sin_port)));
            strcat(buf, "\n");
            
            char join[1024];
            memset(join, 0x00, sizeof(join));
            strcat(join, "@join\n");
            
            int i = 0;
            current = head;
            while(current != NULL){
                if(strcmp(toArray(ntohs(server.sin_port)), toArray(current->port)) && current->room == roomNum){
                    connectToClient(current->IP, toArray(current->port), buf);
                    strcat(join, current->IP);
                    strcat(join, " ");
                    strcat(join, toArray(current->port));
                    strcat(join, " ");
                    strcat(join, current->ID);
                    strcat(join, "\n");
                }
                current = current->next;
            }
            
            if (write(new_sock, join, strlen(join)) < 0) {
                perror("write");
                exit(1);
            }
            find(inet_ntoa(server.sin_addr), ntohs(server.sin_port))->room = atoi(&command[6]);
            printf("room to %d\n", atoi(&command[6]));
            printf("room to %d\n", atoi(&command[6]));
        }
    }
}// main
void 
getEntry(int *team, int *stype)
{


    int     switching = -1;	/* confirm switches 7/27/91 TC */
    inputMask = CP_OUTFIT;
    for (;;) {
	/* updateShips so he knows how many players on each team */
	if (blk_flag)
	    updateShips();
	sendMaskPacket(tournamentMask(me->p_team));
	if (blk_flag)
	    briefUpdateClient();
	flushSockBuf();
	/* Have we been busted? */
	if (me->p_status == PFREE) {
	    me->p_status = PDEAD;
	    me->p_explode = 600;
	}
	socketPause();
	readFromClient();
	if (isClientDead()) {
	    int     i;

	    if (noressurect)
		exitGame();
	    printf("Ack!  The client went away!\n");
	    printf("I will attempt to resurrect him!\n");

	    /* UDP fail-safe */
	    commMode = COMM_TCP;
	    if (udpSock >= 0)
		closeUdpConn();

	    /* For next two minutes, we try to restore connection */
	    shutdown(sock, 2);
	    sock = -1;
	    for (i = 0;; i++) {
		switch (me->p_status) {
		case PFREE:
		    me->p_status = PDEAD;
		    me->p_explode = 600;
		    break;
		case PALIVE:
		case POBSERVE:
		    me->p_ghostbuster = 0;
		    break;
		case PDEAD:
		    me->p_explode = 600;
		    break;
		default:
		    me->p_explode = 600;
		    me->p_ghostbuster = 0;
		    break;
		}
		sleep(5);
		if (connectToClient(host, nextSocket))
		    break;
		if (i == 23) {
		    printf("Oh well, maybe I'm getting rusty!\n");
		    switch (me->p_status) {
		    case PFREE:
			break;
		    case PALIVE:
		    case POBSERVE:
			me->p_ghostbuster = 100000;
			break;
		    case PDEAD:
			me->p_explode = 0;
			break;
		    default:
			me->p_explode = 0;
			me->p_ghostbuster = 100000;
			break;
		    }
		    exitGame();
		}
	    }
	    printf("A miracle!  He's alive!\n");
	    teamPick = -1;
	    updateSelf();
	    updateShips();
	    flushSockBuf();
	}
	if (teamPick != -1) {
	    if (teamPick < 0 || teamPick > 3) {
		warning("Get real!");
		sendPickokPacket(0);
		teamPick = -1;
		continue;
	    }
	    if (!(tournamentMask(me->p_team) & (1 << teamPick))) {
		warning("I cannot allow that.  Pick another team");
		sendPickokPacket(0);
		teamPick = -1;
		continue;
	    }

	    if (((1 << teamPick) != me->p_team) &&
		(me->p_team != ALLTEAM))	/* switching teams 7/27/91 TC */
		if ((switching != teamPick)
		    && (me->p_whydead != KGENOCIDE)
		    && !status2->league
		    ) {
		    switching = teamPick;
		    warning("Please confirm change of teams.  Select the new team again.");
		    sendPickokPacket(0);
		    teamPick = -1;
		    continue;
		}
	    /* His team choice is ok. */
	    if (shipPick < 0 || shipPick >= NUM_TYPES) {
		warning("That is an illegal ship type.  Try again.");
		sendPickokPacket(0);
		teamPick = -1;
		continue;
	    }
	    if (!allowed_ship(1 << teamPick, mystats->st_rank, mystats->st_royal, shipPick)) {
		sendPickokPacket(0);
		teamPick = -1;
		continue;
	    }
	    if (shipvals[shipPick].s_nflags & SFNMASSPRODUCED) {
		warning("o)utpost, u)tility, or s)tandard?");
		sendPickokPacket(0);
		tmpPick = shipPick;
		continue;
	    }
	    break;
	}
	if (me->p_status == PTQUEUE) {
	    if (status->tourn)
		detourneyqueue();
	    /* You don't time out on the tourney queue */
	    me->p_ghostbuster = 0;
	}
    }
    *team = teamPick;
    if ((shipvals[tmpPick].s_nflags & SFNMASSPRODUCED) &&
	((shipvals[shipPick].s_numports) || (shipPick == SCOUT))) {

	*stype = tmpPick;
	tmpPick = CRUISER;
    }
    else {
	*stype = shipPick;
	tmpPick = CRUISER;
    }
    sendPickokPacket(1);
    flushSockBuf();
}
Пример #9
0
int main(int argc, char **argv) {
    // 매개변수 1:자기포트 2:서버IP 3:서버포트 4:자기ID
    int tcpServ_sock;
    
    struct sockaddr_in tcpServer_addr;
    struct sockaddr_in newTcp_addr;
    
    fd_set reads, temps;
    int fd_max;
    
    char command[1024];
    
    if(argc != 5){
        printf("Usage : %s <myport> <serverIP> <serverport> <myID>\n", argv[0]);
        exit(1);
    }
    
    display();
    
    if ((tcpServ_sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket");
        exit(1);
    }// creating socket descriptor for tcp
    
    memset((void *) &tcpServer_addr, 0, sizeof (tcpServer_addr));
    tcpServer_addr.sin_family = AF_INET;
    tcpServer_addr.sin_addr.s_addr = INADDR_ANY;
    tcpServer_addr.sin_port = htons((u_short)atoi(argv[1])); // portnum
    fd_max = 10;
    
    if (bind(tcpServ_sock, (struct sockaddr *)&tcpServer_addr, sizeof (tcpServer_addr)) < 0) {
        perror("bind error");
        exit(1);
    } // bind
    
    if (listen(tcpServ_sock, SOMAXCONN) < 0) {
        perror("listen");
        exit(1);
    } // wait connect
    
    // 여기까지 기본 소켓세팅
    hostIP = argv[2]; // ip
    hostport = argv[3]; // port numbere
    myID = argv[4];
    char buf[1024];
    strcat(buf, "@connect ");
    strcat(buf, myID);
    //peertcpSockets = connectToServer(buf);
    peertcpSockets = connectToServer(buf);
    
    FD_ZERO(&reads);
    FD_SET(fileno(stdin), &reads);
    FD_SET(tcpServ_sock, &reads);
    FD_SET(peertcpSockets, &reads);
    while(1){
        int nfound;
        temps = reads;
        nfound = select(fd_max+1, &temps, 0, 0, NULL);
        // nfound?
        if(FD_ISSET(fileno(stdin), &temps)) {
            // Input from the keyboard
            char sendhttp[1024];
            memset(sendhttp, NULL, sizeof(sendhttp));
            
            
            fgets(command, sizeof (command), stdin);
            
            if( command[0] == '@' ){
                // send to server
                if(command[1] == 'e'){ // when exit
                    head = NULL;
                    peertcpSockets = connectToServer(command);
                    close(peertcpSocket);
                    exit(1);
                }
                peertcpSockets = connectToServer(command);
                FD_SET(peertcpSockets, &reads);
                // exit했을때는 나에게 들어있는 유저목록 다 지워야한다.
            }else{
                node* cnode = head;
                char sendmsg[1024];
                strcat(sendmsg, myID);
                strcat(sendmsg, ") ");
                strcat(sendmsg, command);
                
                while(cnode != NULL){
                    peertcpSockets = connectToClient(head->IP, toArray(head->port), sendmsg);
                    close(peertcpSockets);
                    cnode = cnode->next;
                } // 유저에게 메시지 전송
                close(peertcpSocket);
            }
            fflush(stdin);
        }else if(FD_ISSET(tcpServ_sock, &temps)){
            int addrlen;
            addrlen = sizeof(newTcp_addr);
            peertcpSockets = accept(tcpServ_sock, (struct sockaddr *)&newTcp_addr, (unsigned int*)&addrlen);
            //printf("connection from host %s, port %d, socket %d\n\n",
            //       inet_ntoa(newTcp_addr.sin_addr), ntohs(newTcp_addr.sin_port), peertcpSocket);
            if (peertcpSockets < 0) {
                perror("accept");
                exit(1);
            }
            FD_SET(peertcpSockets, &reads);
            // make connection
        }else if(FD_ISSET(peertcpSockets, &temps)){ // 서버에서 응답받은 내용
            char buf[1024];
            memset(buf, NULL, sizeof(buf));
            read(peertcpSockets, buf, sizeof(buf));
            char tbuf[1024];
            strcpy(tbuf, buf);
            
            char* inif = strtok(tbuf, "\n");
            
            if(!strcmp(touppers(inif),"JOIN")){
                char* temp;
                temp = strtok(buf, "\n");
                printf("%s\n", temp); // 입력받은 첫줄 출력
                
                while((temp = strtok(NULL, "\n")) != NULL){
                    char* tempIP = strtok(temp, " ");
                    char* tempPort = strtok(NULL, " ");
                    int tport = atoi(tempPort);
                    char* tempID = strtok(NULL, " ");
                    insertFirst(tempIP, tport, tempID, 0);
                }
                close(peertcpSockets);
            }else if(!strcmp(touppers(inif),"INVITE OK")){
                printf("%s\n", inif);
                char* temp;
                temp = strtok(NULL, "\n");
                char* tempIP = strtok(temp, " ");
                char* tempPort = strtok(NULL, " ");
                char* tempID = strtok(NULL, " ");
                
                printf("invite %s\n", tempID);
                int tport = atoi(tempPort);
                insertFirst(tempIP, tport, tempID, 0);
                close(peertcpSockets);
                // invite에 성공했다면 그사람을 저장한다.
            }else if(!strcmp(touppers(inif),"@ADD")){
                printf("%s\n", inif);
                char* tempIP = strtok(NULL, " ");
                char* tempPort = strtok(NULL, " ");
                char* tempID = strtok(NULL, " ");
                
                int tport = atoi(tempPort);
                insertFirst(tempIP, tport, tempID, 0);
                close(peertcpSockets);
                // close 소켓 서버에서?유저에서?
            }else if(!strcmp(touppers(inif),"@DELETE")){
                printf("%s\n", inif);
                char* tempIP = strtok(NULL, " ");
                char* tempPort = strtok(NULL, " ");
                int tport = atoi(tempPort);
                deletes(tempIP, tport);
                close(peertcpSockets);
            }else{
                printf("%s\n",buf); // print receive msg
                close(peertcpSockets);
                //FD_CLR(peertcpSockets, &reads);
            }
            buf[0] = '\0';
            printf("> ");
        }// receive
        
        fflush(stdout);
    }
}//main End