从 Socket.Receive TCP C# 接收数据时应用程序崩溃

Application crash when receiving data from Socket.Receive TCP C#

我有一个聊天室应用程序,它包含服务器和客户端两部分。
服务器部分可以接收来自多个客户端的数据。到目前为止一切顺利。
但是当其中一位客户离开时,软件出现错误!

这是服务器源代码:
我评论了软件报错的那一行!!!

Socket _server;
private void StartServer()
{
    _server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    _server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 100010));
    _server.Listen(1);

    while (true) {
        Socket client = _server.Accept();
        Thread rd = new Thread(ReceiveData);
        rd.Start(client);
    }
}

public void ReceiveData(object skt)
{
    Socket socket = (Socket)skt;
    while (true) {
        byte[] buffer = new byte[1024];
        int r = socket.Receive(buffer);// when a client leave here get an error !!!
        if (r > 0)
            Console.WriteLine(socket.RemoteEndPoint.Address + ": " + Encoding.Unicode.GetString(b));
    }
}

错误:

An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll

Additional information: An existing connection was forcibly closed by the remote host

我该如何解决?

您应该只处理异常:

try
{
    // code that uses the socket
}
catch (SocketException e) when (e.SocketErrorCode is SocketError.ConnectionAborted)
{
    // code to handle the situation gracefully
}

或者,如果您使用的是旧版编译器:

try
{
    // code that uses the socket
}
catch (SocketException e)
{
    if(e.SocketErrorCode != SocketError.ConnectionAborted)
    {
        // rethrow the exception
        throw;
    }

    // code to handle the situation gracefully
}