I have written a Server using WINAPI with CreateThread() Method. The first connection request always dies. All the following requests/threads are working as expected. I have no idea why so i hope someone could tell me. Here is a working example illustrating the issue.
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;
}