我已经使用带有 CreateThread() 方法的 WINAPI 编写了一个服务器。第一个连接请求总是终止。以下所有请求/线程都按预期工作。我不知道为什么,所以我希望有人能告诉我。这是一个说明问题的工作示例。
DWORD WINAPI process_thread(LPVOID lpParam) {
SOCKET current_client = (SOCKET)lpParam;
char buf[1024];
int res;
while(1) {
res = recv(current_client, buf, strlen(buf), 0);
if(res>0) {
buf[res] = '\0';
send(current_client, buf, strlen(buf), 0);
}
}
}
int main() {
SOCKET sock;
DWORD thread;
WSADATA wsaData;
SOCKADDR_IN server;
WSAStartup(0x102,&wsaData);
server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=htons(123);
sock=socket(AF_INET,SOCK_STREAM,0);
bind(sock,(SOCKADDR*)&server,sizeof(server));
listen(sock,5);
SOCKET client;
SOCKADDR_IN from;
int fromlen = sizeof(from);
while(1) {
client = accept(sock,(struct SOCKADDR*)&from,&fromlen);
CreateThread(NULL, 0,process_thread,(LPVOID)client, 0, &thread);
}
closesocket(sock);
WSACleanup();
return 0;
}