C# 无法从传输连接中读取数据: 远程主机强迫关闭了一个现有的连接。。

http://blog.sina.com.cn/s/blog_5f2833390100nked.html
关于客户端断开连接的时候,服务端会catch到一个socketException端口异常提示,无法从传输连接中读取数据: 远程主机强迫关闭了一个现有的连接。。此时,如果按以下写法,服务器没法再接收到新的数据

           public void TCPStart()
        {
            try
            {
                tcpListener = new TcpListener(IPAddress.Parse(publicClass.GetLoaclIP()), TCPlistenerPort);
                tcpListener.Start();
                while (true)
                {
                    allDone.Reset();
                    tcpListener.BeginAcceptTcpClient(new AsyncCallback(AcceptCallBack), tcpListener);
                    allDone.WaitOne();
                }
            }
            catch (Exception ex)
            {
                MainForm.NowForm.Invoke(MainForm.NowForm.delegateSetState, new string[] { "Err:" + ex.Message });
            }
        }


其实原因很简单,把try写进循环里面就行了,得细心一点才行啊!!
      public void TCPStart()
        {
            tcpListener = new TcpListener(IPAddress.Parse(publicClass.GetLoaclIP()), TCPlistenerPort);
            tcpListener.Start();
            while (true)
            {
                try
                {
                    allDone.Reset();
                    tcpListener.BeginAcceptTcpClient(new AsyncCallback(AcceptCallBack), tcpListener);
                    allDone.WaitOne();
                }
                catch (Exception ex)
                {
                    MainForm.NowForm.Invoke(MainForm.NowForm.delegateSetState, new string[] { "Err:" + ex.Message });
                }
            }
        }
展开阅读全文

没有更多推荐了,返回首页