Greetings all.
I have almost no experience with Network programming on C#.
I have an Asynchronous UDP socket on a server that sends data to clients.
If one of the client crashes i get the next Socket Error:
Message = "An existing connection was forcibly closed by the remote host"
ErrorCode = 10054
SocketErrorCode = ConnectionReset
How do you handle this exception???
I cant close the socket because there are other clients still receiving messages. I also cant ignore the ICMP message, because i need remove the client from a local list.
The code:
public void Initialize()
{
receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
receiveEndPoint = new IPEndPoint(IPAddress.Any, receivePort);
receiveSocket.Bind(receiveEndPoint);
receivePort = (receiveSocket.LocalEndPoint as IPEndPoint).Port;
receiveBuffer = new byte[BufferSize];
receiveAsyncResult = receiveSocket.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref receiveEndPoint, new AsyncCallback(NetworkMessageReceivedCallback), receiveSocket);
........
......
}
protected void NetworkMessageReceivedCallback(IAsyncResult asyncResult)
{
EndPoint remoteEndPoint = null;
byte[] bytes = null;
try
{
remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
int bytesRead = receiveSocket.EndReceiveFrom(asyncResult, ref remoteEndPoint);
bytes = new Byte[BufferSize];
Buffer.BlockCopy(receiveBuffer, 0, bytes, 0, bytesRead);
receiveAsyncResult = receiveSocket.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None,
ref receiveEndPoint, new AsyncCallback(NetworkMessageReceivedCallback), receiveSocket);
}
catch (SocketException socketException)
{
if (OnForceDisconnect != null) { OnForceDisconnect(remoteEndPoint); }
receiveAsyncResult = receiveSocket.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None,
ref receiveEndPoint, new AsyncCallback(NetworkMessageReceivedCallback), receiveSocket);
}
..........
}
Thanks