Hi all,
I am constructing a program on TCP sockets. The server should be able to accept connections from more than 1 clients. My programs seem working fine when accepting connections. Now the problem is: when I try to terminate one of the client programs,
the server program would also terminate due to error in accept() (of course other client programs would terminate as well because the server shuts down). How can I keep the server running for listening and accepting new connections?
Any help would be appreciated! Thanks in advance :)
/******************** Threading ********************/
DWORD WINAPI receive_cmds(LPVOID lpParam) {
SOCKET current_client = (SOCKET)lpParam;
/* Do some server stuffs here*/
closesocket(current_client);
WSACleanup();
ExitThread(0);
}
/******************** Main program ********************/
int main() {
SOCKET server_sockfd, client_sockfd;
int client_len, server_len;
int optsize = sizeof(BOOL);
char optval = '1';
struct sockaddr_in server_address, client_address;
DWORD thread;
WSADATA wsadata;
if(WSAStartup(0x101,(LPWSADATA)&wsadata) != 0) {
WSACleanup();
exit(1);
}
RESETPORT:
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(server_sockfd, SOL_SOCKET, SO_KEEPALIVE, &optval, optsize);
setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, optsize);
if(server_sockfd == SOCKET_ERROR) {
WSACleanup();
exit(1);
}
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = 5200;
server_len = sizeof(server_address);
if(bind(server_sockfd, (struct sockaddr *)&server_address, server_len) < 0) {
WSACleanup();
exit(1);
}
if(listen(server_sockfd, 2) < 0) {
WSACleanup();
exit(1);
}
client_len = sizeof(client_address);
while(1) {
client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len);
if(client_sockfd == SOCKET_ERROR) {
WSACleanup();
goto RESETPORT;
}
CreateThread(NULL, 0, receive_cmds,(LPVOID)client_sockfd, 0, &thread);
}
closesocket(server_sockfd);
WSACleanup();
return 0;
}