My task is to implement a two-user game between two computers connected via TCP. One of the requirements is that only the winner gets the choice of the game again or not. If the server wins and decides not to play further, the client must restart as a server and accept new connections.
My approach: If the game is LOST (in client mode), close sockfd and recreate another one. Then use setsockopt to enable reconnection with SO_REUSEADDR and then call bind.
int yes = 1; if ( setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1 ) { perror("setsockopt"); } if ( bind(sockfd, (struct sockaddr*)&svr, sizeof(svr) ) == -1 ) { perror("server: bind"); }
But still, I get the same "Address already in use" error. I tried to sleep for 150 seconds before recreating the socket, and this method works.
NOTE. I am testing this on the same PC. It can work on two connected computers, but it must be made to work on one PC. Please, help.
source share