c – TCP Winsock:接受多个连接/客户端
作者:互联网
我试图将客户端倍增,并将其发送给每个客户端.
但它只适用于一个,在一个客户端连接服务器后,只是无法用于传入连接.
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;
}
}
解决方法:
当然,新客户端不能被接受,因为服务器只处理接受的客户端,即服务器正忙.
解决方案很简单:为每个接受的客户端创建一个新线程,并在那里处理客户端会话.只需使用_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,sockets,tcp,winapi,winsock2 来源: https://codeday.me/bug/20190927/1824155.html