1

クライアント TCP/IP アプリケーションでSocketクラスを使用して、クライアントをサーバーに接続しています。

次のコードがあります。

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);
    }
} 

ここにソケットエラーのリストがあります。

そのため、ある時点でサーバーが接続を閉じるとき、サーバーが別の接続を受け入れる準備ができていることを知るための最良の方法と、同じエンドポイントに再度接続する方法を知る必要があります。

4

1 に答える 1

1

WSAECONNREFUSEDは、サーバーが接続要求を受け入れていないことを意味します。

再試行の間に数秒スリープして、ループで接続を再試行する必要があります。接続を試みずに、クライアントがサーバーがいつ再び利用可能になるかを知る方法はありません。

于 2012-11-07T15:37:03.170 に答える