Soran
Soran

Reputation: 391

Winsock - reconnecting client to server - 10061

I thought I would start a new question for this. I have a TCP server/client set up and they communicate the way I generally want. 1 server and 1 client.

What I want to do now is add functionality that would allow the client to automatically reconnect to the server once a connection is lost. I'm having trouble finding complete information online on how to do this. This is (hopefully) the relevant problem code:

SERVER:

    case FD_ACCEPT: //Connection request  
    {  
        SOCKET TempSock = accept(s, (struct sockaddr*)&fromm, &fromlenn);  
        s = TempSock; //Switch old socket to the new one  
        m_sNetworkStatus.Format("[%s] accepted.", inet_ntoa(fromm.sin_addr));  
        m_hNetworkStatus.SetWindowTextA(m_sNetworkStatus);  
    }  

The first client connection goes through fine. The server listens, the client connects, the client disconnects... BUT the second time the client tries to connect the resultant client IP address (as seen by the server) is such that printing inet_ntoa(fromm.sin_addr)) will output [0,0,0,0]. So, the client 'thinks' it's connected but it is not and the server prints that it accepted the connection but no data can be sent...disconnecting on the client side and attempting to reconnect again leads to a

connection refused 10061 error.

(If I disconnect from the server side and listen to a new port there's no problem)

Thanks !!!

Upvotes: 2

Views: 1913

Answers (1)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84239

You are overwriting your listening server socket s with the result of the accept(), i.e. the connected socket. This is totally wrong - you are supposed to reuse that same server socket you called listen() on for all subsequent calls to accept(), which will give you a new socket every time each representing full new TCP connection from a client.

Upvotes: 1

Related Questions