I have a fairly simple client/server structure using System.Net.Sockets, where the server only sends data to a collection of clients, and the clients only receive data, so, the data flow is unidirectional. My server sends the same data to each of the connected clients, at the same time through a for loop. The loop sends the data, or removes the client if it has disconnected. My problem is when the client disconnects, it can cause the server program to pause.
This is where the server distributes the data:
-
for (int i = Clients.Count - 1; i >= 0; i--)
-
{
-
if (((Client)Clients[i]).isAlive() && serve)
-
{
-
((Client)Clients[i]).send(data.get_bytes());
-
}
-
else
-
{
-
((Client)Clients[i]).Stop(); // releases resources associated w/ client
-
Clients.RemoveAt(i);
-
}
-
Also in the server code, there is a client handling class, and this is the send function used above:
-
-
try
-
{
-
ns.Write(sendB, 0, sendB.Length);
-
}
-
catch (***Exception) { } //if there's an error i will say that the client has disconnected, and isAlive = false;
-
I would like to keep it simple and have the client disconnect, whether or not the client disconnected on purpose, or the connection is cut. The actual client code is simple, and just sits in a loop waiting to call the NetworkStream read() call. I'm sure there's a better and more efficient way of handling the client disconnecting, b/c i don't want this to affect the remaining clients, if one disconnects for any reason. Any ideas? Thanks.