Reputation:
I'm currently receiving a strange error, and want to handle it for 1 specific case. When the server closes and the client is still connected to it, the client will throw an exception
System.Net.Sockets.SocketException: 'An existing connection was forcibly closed by the remote host'
I know how to handle this, a try and catch, but am I handling more than one reason this exception would be thrown here? I just want to handle it if the server closes, not all of the other reasons this exception may suddenly occur. Can anybody help here?
What line is the error occuring on?
var bytesReceived = _socket.EndReceive(asyncResult);
What method?
private void OnIncomingData(IAsyncResult asyncResult)
Method content
var bytesReceived = _socket.EndReceive(asyncResult);
try
{
var packet = new byte[bytesReceived];
Array.Copy(_buffer, packet, bytesReceived);
var received = Encoding.UTF8.GetString(packet);
CoreUtilities.LogToConsole("Received data: " + received);
}
catch
{
Dispose();
}
finally
{
try
{
_socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, OnIncomingData, _socket);
}
catch
{
}
}
Upvotes: 1
Views: 422
Reputation: 2940
You could handle this using the SocketErrorCode
property which part of SocketException. According to this TechNET article (I couldn't find anything on MSDN), the error code should be 10054 which matches with the SocketError.ConnectionReset
enum value as shown below:
Example of handling the specific error:
try
{
_socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, OnIncomingData, _socket);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.ConnectionReset)
{
//Do Something
}
}
Upvotes: 1