简体   繁体   中英

Trouble disconnecting and reconnecting socket (C++, winsock2)

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()sa 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM