Domanda

I'm using the Socket class in a client TCP/IP application to connect my client to a server.

I have the following code:

var endPoint = new IPEndPoint(IPAddress.Parse(IP), port);
var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                        ProtocolType.Tcp);

client.Connect(endPoint);

try
{
    while (true)
    {
        // Do work...
        // Receive/Send data from/to server
    }
}
catch (SocketException)
{
    /* At some point the server disconnects...
    Exception catched because the server close the connection
    Socket error 10054 - WSAECONNRESET */

    // So I try to reconnect
    if(client.Connected == false)
    {
        /* The following line throws a InvalidOperationException.
        Message: After disconnecting the socket, you can reconnect only 
        asynchronously from a different EndPoint. BeginConnect must be 
        called on a thread that will not close until the operation completes.*/
        client.Connect(endPoint);   

        /* So I try instead Socket.BeginConnect, but the following line
        throws a SocketException 10061 - WSAECONNREFUSED */
        client.BeginConnect(endPoint, ConnectCallback, client);

        /* And also the following code throws a 
            SocketException 10061 - WSAECONNREFUSED */
        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                                ProtocolType.Tcp);
        client.Connect(endPoint);
    }
} 

Here a list of socket error.

So, at some point the server close the connection, I need to know what is the best method to know when the server is ready for accept another connection and how to connect again to the same End Point.

È stato utile?

Soluzione

WSAECONNREFUSED means, the server is not accepting your connection request.

You will have to retry to connect in a loop with sleeping a few seconds between the retries. There is no way for the client to know when the server is available again, without trying to connect.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top