I'm still figuring out this low-level network communications thing so bear with me.
In a client-server environment (simple chat app) with multiple clients "connected," is it possible to reuse the same socket to broadcast a message to all the the clients? I put connected in quotes as no client maintains a TCP connection on it's own socket but the server maintains a list of IP Address/port that the client applications are listening on. I am just trying to get the broadcast function to work and will worry about handling disconnected clients later.
Now, when there is only one client connected, this code works just fine. As soon as another client connects, it dies when it tries to loop through.
private void TransmitToAll(byte[] message)
{
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
foreach (ChatConnection conn in _connectedClients)
{
soc.Connect(conn.Address, 25001);
soc.Send(message);
soc.Disconnect(true);
}
soc.Dispose();
}
The error that it gives me is:
Once the socket has been disconnected, you can only reconnect again asynchronously, and only to a different EndPoint. BeginConnect must be called on a thread that won't exit until the operation has been completed.
For this first attempt, I would like to keep with a synchronous broadcast process so using async sockets is not on the table yet (that comes later).
What I have tried:
I have tried to reconfigure this code in multiple ways but it still fails. I know that I could easily just create a new socket for each broadcast but that feels wrong and just plain inefficient. I've tried different socket options such as setting
DontLinger
to false but that had no effect.