Winsock problem: connect() works on the client side but accept() blocks on the server side
Tuesday 29 January 2008While writing a proof-of-concept Winsock program, I run into an issue that is worth sharing, especially with Winsock beginners. I hadn’t done socket programming for a while, so forgive my stupidity.
Basically, I had the server code to do this :
-
while (true)
-
{
-
//…
-
serverSocket = socket(…);
-
setsockopt(serverSocket, SO_REUSEADDR, …);
-
bind(serverSocket, …);
-
listen(serverSocket, portNumber);
-
clientSocket = accept(…);
-
// do something with the client
-
}
This was working for the first 2 calls of the client, but at the 3rd call, the client’s connect() would work and the server would be stuck on the accept().
Foolish me! After a little investigation, I realized you don’t put the listen() call inside the server loop…
Here’s the proper code:
-
//…
-
serverSocket = socket(…);
-
setsockopt(serverSocket, SO_REUSEADDR, …);
-
bind(serverSocket, …);
-
listen(serverSocket, portNumber);
-
while (true)
-
{
-
clientSocket = accept(…);
-
// do something with the client
-
}
Hope this helps…





