我正在构建一个服务器,该服务器在多个端口上侦听多个客户端连接。我正在使用线程来处理这些连接中的每一个。但是,当> 2个客户端连接到端口时,服务器将不处理以下连接。不确定是连接问题还是线程问题。两者都是新手。
/** Thread started by the client that has connected
*
*
*
*/
void* client_listener(void* client){
printf("Client for thread started\n");
fflush(stdout);
return NULL;
}
/** Listen for clients for this game
*
*
*
*/
void* listen_now(void* gameStruct){
Game* thisGame = (Game*) gameStruct;
listen(thisGame->sockfd, thisGame->totalPlayers);
int playerAdded = 0;
struct sockaddr_in cli_address;
socklen_t clilen = sizeof(cli_address);
//Keep accepting new connections
while((accept(thisGame->sockfd, (struct sockaddr*) &cli_address, &clilen) > 0)){
//Make the player in the game
printf("Total Players accepted is %d\n", playerAdded);
fflush(stdout);
//Make a client to store in the game struct
Client* thisPlayer = make_client(thisGame, thisGame->clientSockfd[thisGame->gameId]);
thisPlayer->cli_address = cli_address;
//Save values to this Client
thisPlayer->id = playerAdded;
pthread_t clientThread = thisPlayer->clientThread;
//Create thread for this client
pthread_create(&clientThread, NULL, client_listener, &thisPlayer);
playerAdded++;
}
}
/** Get the socket for the port
*
*
*/
int get_socket_for_port(Game* game, int port){
int sockfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
game->server_address.sin_family = AF_INET;
game->server_address.sin_port = htons(port);
game->server_address.sin_addr.s_addr = INADDR_ANY;
if(bind(sockfd, (struct sockaddr*) &game->server_address, sizeof(game->server_address))<0){
printf("bind failed");
}
return sockfd;
}
/** Setup the game threads
*
*
*/
void setup_game(Server* server){
pthread_t gameThreads[server->numberOfGames-1];
Game* traversal = server->game;
int gameId;
//Loop through the games and setup their ports to listen on
while(traversal!=NULL){
traversal->clientSockfd = (int*) malloc(traversal->totalPlayers*sizeof(int));
//Get the sockfd for the port
int sockfd = get_socket_for_port(traversal, traversal->port);
//Save the socketfd for this game to struct
traversal->gameId = gameId;
traversal->sockfd = sockfd;
//Create a gameThread
pthread_create(&gameThreads[gameId], NULL, *listen_now, traversal);
gameId++;
traversal = traversal->nextGame;
}
}
当我将4次连接到端口时,服务器正在监听。我得到以下输出。不确定,并且对了解可能发生的事情感兴趣。
输出: 接受的玩家总数为0
客户端线程已启动
接受的玩家总数为1
客户端线程已启动
接受的玩家总数为2