简体   繁体   中英

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

i have an chat room application that has two parts server and client.
server part can receive data from multi clients. So far so good.
But when one of the client leaves, the software gets an error!

this is server source code:
I commented on the line where the software gets an error !!!

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));
    }
}

Error:

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

How can i fix it?

You should just handle the exception:

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

Or if you are using an older compiler:

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

    // code to handle the situation gracefully
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM