检查Tcp断开连接的最佳方法是什么?

时间:2018-08-15 10:46:03

标签: c#

我正在使用TCP使用C#编写聊天程序,但无法处理断开连接。我需要确保可以检测到断开连接是手动还是客户端断开连接。

我只是尝试关闭客户端和流,但是它们并没有像我认为的那样在服务器中引发异常。

还需要这样做吗?

byte[] receive = new byte[10240];
int bytesReceived = 0;

try
{
    while (bytesReceived < receive.Length)
    {
        bytesReceived += Stream.Read(receive, 0, receive.Length);
    }
 }

我添加了此代码以确保它获取所有字节,但是我不确定是否需要这样做。

编辑:将其更改为此,并且可以使用。感谢Jeroen Mostert的帮助。

            byte[] receive = new byte[10240];
            int bytesRead = 0;

            try
            {
                bytesRead = Stream.Read(receive, 0, receive.Length);
            }
            catch (IOException e)
            {
                if (e.InnerException.GetType() == typeof(SocketException))
                {
                    SocketException socketExc = (SocketException)e.InnerException;

                    if (socketExc.SocketErrorCode == SocketError.Interrupted)
                    {
                        Running = false;
                        continue;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }

            if (bytesRead == 0)
            {
                Running = false;
                continue;
            }

0 个答案:

没有答案