I have a console application as server socket that broadcast messages to all connected clients as also console applications, where sometimes when one client is disconnected then the server process get crashed without even raising any exception while I have try/catch blocks everywhere, but it seems it is windows level error as it logs one error in the event viewer that is (Exception code: 0xc0000005), I noticed that if I just comment the socket Send line (in the code below) then the crash won’t happen anymore, where the Send method is inside a for loop that send messages to all client in milliseconds, so am just wondering how to manage this expected scenario that during sending to a client then the client is subject to disconnect, here is how my code looks like:
//I have global collection for all connected clients
Dictionary<int, Socket> Clients = new Dictionary<int, Socket>();
// this method is called in milliseconds
void Broadcast(byte[] data)
{
List<int> disconnected = new List<int>();
foreach (KeyValuePair<int, Socket> socket in Clients)
{
try
{
socket.Value.Send(data);
}
catch (Exception e)
{
IPEndPoint ep = (IPEndPoint) socket.RemoteEndPoint;
disconnected.Add(ep.Port);
}
}
foreach(int port in disconnected)
{
Clients.Remove(port);
}
}