我正在制作一个有 2 个线程的套接字服务器,每个线程都在一个循环中运行。第一个查找新连接,第二个从已连接的套接字中读取数据并回复它们。问题出在第二个。'write' 函数以某种方式打破循环并导致程序完成......没有错误发生......这就是问题所在。
以下代码是第二个线程的函数。如果我不向套接字写入任何内容,则程序运行良好
void* SocketServer::threadSocketsRead( void* thisServer )
{
SocketServer* server;
int key,
playersNumber,
requestLength;
Player* player;
char message[256];
string reply;
server = (SocketServer*)thisServer;
while ( 1 )
{
playersNumber = server->players.size();
for ( key = 0 ; key < playersNumber ; key ++ )
{
player = server->players[key];
requestLength = read ( player->socket , (void*)&message , 255 );
if ( requestLength < 0 )
{
perror ( "read" );
}
else
{
/*
If I uncomment the line, it will write data to
the socket and finish the whole program.
If I do no uncomment it, the programs runs in a loop further.
*/
//int result = write ( player->socket , "reply\0" , 6 );
};
}
sleep(1);
}
}