网络拔掉后,C#TcpClient无法重新连接

时间:2014-02-13 13:30:17

标签: c# networking tcpclient reconnect

网络拔出后再次连接,客户端无法重新连接到服务器,直到再次停止并启动客户端服务。我得到以下异常:

  

无法建立连接,因为目标计算机主动拒绝它

再次插入后。

此外,由于tcpClientnull,我无法关闭该流。

这是连接代码:

private void BeginConnect()
{
    try
    {
        tcpClient = new TcpClient(this.serverIP, this.serverPort);
    }
    catch (Exception ex)
    {
       //i get "No connection could be made because the target machine actively refused it" here
        Disconnect();
    }
}

public void Disconnect()
{
    try
    {
        tcpClient.GetStream().Close();
        tcpClient.Client.Disconnect(false);
        tcpClient.Close();
    }
    catch
    {
        ; // exception: "Object reference not set to an instance of an object"
    }
    tcpClient = null;
}

如何在不重新启动服务的情况下强制关闭并创建新连接?

0 个答案:

没有答案
相关问题