【问题标题】:TCP Client Not Reconnecting After Disconnect断开连接后 TCP 客户端未重新连接
【发布时间】:2017-01-15 21:17:55
【问题描述】:

我已经制作了一个服务器和一个客户端。如果我关闭服务器,客户端应该重新尝试连接到服务器。我已经做到了,所以当 waitForCommands 期间的 try/catch 失败时,它会在新线程中重新启动尝试连接方法。我在这里遇到的问题是它根本不会重新连接。作为测试,我打开了我的 TCP 服务器和 TCP 客户端。客户端像往常一样连接到服务器。然后,我关闭 TCP 服务器,客户端快速吐出这个错误:'System.Net.Sockets.SocketException',并且永远不会连接。

class Program
{
    public static TcpClient client = new TcpClient();
    public static NetworkStream stream;
    public static byte[] readBuffer;

    static void Main(string[] args)
    {
        new Thread(attemptConnection).Start();
    }

    public static void waitForCommands()
    {
        while (client.Connected)
        {
            try
            {
                readBuffer = new byte[client.ReceiveBufferSize];
                int data = stream.Read(readBuffer, 0, readBuffer.Length);
                string plainText = Encoding.ASCII.GetString(readBuffer, 0, data);
                if (plainText.Contains("mbox"))
                {
                    MessageBox.Show("");
                }
            }

            catch
            {
                new Thread(attemptConnection).Start();
            }

        }
    }

    public static void attemptConnection()
    {
        while(!client.Connected)
        {
            try
            {  
                client.Connect("127.0.0.1", 23154);
                stream = client.GetStream();
                new Thread(waitForCommands).Start();
            }

            catch(Exception ex)
            {
                Console.WriteLine(ex.Data);
            }
        }

    }
}

我注意到一个有趣的事情,如果我写 'client.Close();'在服务器退出事件中,当客户端尝试重新连接时,我没有收到任何错误消息。它只是显示一个空白屏幕,什么都不做

如果您想在我的服务器上查看等待连接的代码,这真的很简单,所以我不确定为什么会出现这个问题。

    public static void waitForConnection()
    {
        server.Start();
        client = server.AcceptTcpClient();
        stream = client.GetStream();
        f.labelControl1.Text = "Connected";
    }

【问题讨论】:

  • 您必须为您的客户端变量分配一个新的 TcpClient 实例。
  • 谢谢,解决了。我不明白是怎么回事,但确实如此。

标签: c# sockets tcp


【解决方案1】:

为了扩展我的评论,我认为这是由于底层 TCP 连接(网络流)没有自动关闭。

尝试手动关闭流,看看它做了什么:

client.GetStream().Close();

您也可以只关闭为您关闭流的客户端(请参阅https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.close.aspx):

client.Close();

还有另一种解决问题的方法(请参阅https://stackoverflow.com/a/38006848/4408417):

client.Client.Disconnect(true);

【讨论】:

    【解决方案2】:

    我将 client.Connect() 更改为

    client = new TcpClient();
    client.Connect("127.0.0.1", 23154);
    

    正如 Jasper 在 cmets 中推荐的那样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 2022-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多