C#WinForms(TcpClient)-无法从传输连接读取数据/向传输连接写入数据:远程主机强制关闭了现有连接

本文关键字:连接 数据 传输 程主机 主机 TcpClient 读取 C#WinForms | 更新日期: 2023-09-27 18:27:10

我意识到有很多关于这个问题的文章,但我很难找到这个特定问题的解释。

服务器是一个Asterisk PBX服务器,它不断地将呼叫数据写入套接字。

目前,大约有10个客户端连接到服务器,它们随机出现无法读取/写入传输连接的异常。这可能是程序加载时的第一次读/写,也可能是4小时后。这个问题没有一致性或模式。客户端不是在同一时间而是在不同的时间接收这些信息。

有人知道为什么会发生这种事吗?此外,因为我是网络编程的新手,当发现此异常时,将tcp客户端重新连接到服务器的最佳和最优雅的方法是什么?

提前谢谢。

    private TcpClient client;
    private NetworkStream stream;
    private Encoding encoding;
    private void frmMain_Load(object sender, EventArgs e)
    {   
        this.client = new TcpClient("192.168.0.100", 5038);
        this.stream = this.client.GetStream();
        this.encoding = Encoding.ASCII;
        if (client.Connected)
            BeginRead();
    }
    private void BeginRead()
    {
        try
        {
            NetworkStream stream = this.client.GetStream();
            byte[] buffer = new byte[client.ReceiveBufferSize];
            IAsyncResult ar = stream.BeginRead(buffer, 0, buffer.Length, OnReadComplete, buffer);
        }
        catch (IOException ioex)
        {
            //Unable to read data from the transport connection caught here.
            //How to reconnect gracefully?
        }
        catch (Exception ex)
        {
            //Handle...
        }
    }
    private void OnReadComplete(IAsyncResult ar)
    {
        try
        {
            NetworkStream stream = this.client.GetStream();
            byte[] buffer = (byte[])ar.AsyncState;
            int bytesRead = stream.EndRead(ar);
            if (bytesRead > 0)
            {
                //Process response here...
            }
            BeginRead();  //Read again after read completed
        }
        catch (Exception ex)
        {
            //Handle...
        }
    }
    private void BeginWrite(string msg)
    {
        try
        {
            byte[] data = encoding.GetBytes(msg);
            IAsyncResult ar = stream.BeginWrite(data, 0, data.Length, this.OnWriteComplete, stream);
            stream.Flush();
        }
        catch (IOException ioex)
        {
            //Unable to write data to the transport connection caught here.
            //How to reconnect gracefully?
        }
        catch (Exception ex)
        {
            //Handle...
        }
    }
    private void OnWriteComplete(IAsyncResult ar)
    {
        try
        {
            NetworkStream arStream = (NetworkStream)ar.AsyncState;
            arStream.EndWrite(ar);
        }
        catch (Exception ex)
        {
            //Handle...
        }
    }

C#WinForms(TcpClient)-无法从传输连接读取数据/向传输连接写入数据:远程主机强制关闭了现有连接

我怀疑这是因为您忘记了"关闭"NetworkStream"对象。如果你不这样做,GC会的。然而,当GC收集"NetworkStream"对象时是不确定的,这就是为什么您会看到这种随机行为。