我试图增加客户数量,并将其发送给每个客户。 但它仅适用于一个客户端,在一个客户端连接到服务器后,服务器对传入连接毫无用处。
while(true)
{
if(Sub = accept(Socket, (sockaddr*)&IncomingAddress, &AddressLen))
{
for(int i = 0; i < MaxUsers; i++)
{
if(!ClientAddress[i].sin_family)
{
ClientAddress[i] = IncomingAddress;
char Version[128], Dir[256], Path[256], URL[128], Message[256];
GetCurrentDirectory(256, Dir);
sprintf(Path, "%s\\Version.ini", Dir);
GetPrivateProfileString("Default", "Version", "1.0.0.0", Version, 128, Path);
GetPrivateProfileString("Default", "URL", "", URL, 128, Path);
GetPrivateProfileString("Default", "Message", "", Message, 256, Path);
send(Sub, Version, 128, 0);
send(Sub, Message, 256, 0);
break;
}
}
continue;
}
}
最佳答案
当然不能接受新客户端,因为服务器处理刚刚接受的客户端,即服务器正忙。
解决方案很简单:为每个接受的客户端创建一个新线程并在那里处理客户端 session 。只需使用 _beginthreadex()
( #include <process.h>
):
unsigned __stdcall ClientSession(void *data)
{
SOCKET client_socket = (SOCKET)data;
// Process the client.
}
int _tmain(int argc, _TCHAR* argv[])
{
...
SOCKET client_socket;
while ((client_socket = accept(server_socket, NULL, NULL))) {
// Create a new thread for the accepted client (also pass the accepted client socket).
unsigned threadID;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &ClientSession, (void*)client_socket, 0, &threadID);
}
}
顺便说一下,send()/recv()
函数不保证所有数据将在一次调用中发送/接收。有关这些函数的返回值,请参阅文档。
关于c++ - TCP 温索克 : accept multiple connections/clients,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15185380/