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

Time:03-20

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 ?

CodePudding user response:

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
}
  • Related