0
votes

I want the client program (TCP) to be ready to connect to the server program whenever the server starts to accept() incoming connections (the client program should always stay running, and the server program can start or end whenever it wants). The client code looks like this:

while (1) {

    //Wait for the server to accept the connection:
    while (connect(socket,(sockaddr*)&addr,sizeof(addr))!=0) {cout<<WSAGetLastError()<<endl;}

    //Send whatever data...

}

On the first execution of the while (1) loop, everything runs as expected; when the client is connected to the server, it sends all the data, and the the server program is ended. Then I want the client to wait again at the while (connect(...,...,...)!=0) loop until the server starts again and accept()s a connection, but it does not connect to the server and WSAGetLastError() returns 10056, indicating that the socket is already connected (why?). I heard that you cannot reconnect the client after calling closesocket() on the socket, so I tried to disconnect the client before reconnecting by adding shutdown(socket,SD_SEND) to the while (1) loop but that doesn't work either.

Is there anything I can do besides repetitively waiting for the client program to end and starting it again? Is there some way to disconnect the client from the server program such that the client can reconnect later?

1
What??? Close the socket! 'I heard that you cannot reconnect the client after calling closesocket() on the socket' - where did you hear that?Martin James
When the server program ends, does it close its end of the connection? It should do.Martin James
@MartinJames it doesn't close the connection ._. It keeps returning 10056 no matter how long I wait...Awais Chishti
Never mind me - I'm tired and starting to spout nonsense. In my apps, I create another socket at the top of the 'connect/read/close' loop. I was wrong. Obviously, this reloads the same socket var with a new socket.Martin James

1 Answers

2
votes

There's something seriously wrong with your application logic. You don't need to reconnect a connected socket; you can't reconnect a connected socket; and you can't reconnect a socket that has been closed, unless you're exploring one of the remote corners of the Windows API.