【问题标题】:Connect to the same End Point using Socket使用 Socket 连接到同一个端点
【发布时间】:2012-10-27 15:11:15
【问题描述】:

我在客户端 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);
    }
} 

Here 套接字列表错误。

所以,在某些时候服务器关闭连接,我需要知道什么是最好的方法来了解服务器何时准备好接受另一个连接以及如何再次连接到同一个端点。

【问题讨论】:

    标签: c# sockets client endpoint reconnect


    【解决方案1】:

    WSAECONNREFUSED 表示,服务器不接受您的连接请求。

    您将不得不重试连接,并在两次重试之间休眠几秒钟。如果不尝试连接,客户端无法知道服务器何时再次可用。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-30
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多