I have a TCP server that continually monitors for new incoming clients asynchronously and adds them to a client list:
public class TcpServer
{
public List<TcpClient> ClientsList = new List<TcpClient>();
protected TcpListener Server = new TcpListener(IPAddress.Any, 3000);
private _isMonitoring = false;
public TcpServer()
{
Server.Start();
Server.StartMonitoring();
}
public void StartMonitoring()
{
_isMonitoring = true;
Server.BeginAcceptTcpClient(HandleNewClient, null);
}
public void StopMonitoring()
{
_isMonitoring = false;
}
protected void HandleNewClient(IAsyncResult result)
{
if (_isMonitoring)
{
var client = Server.EndAcceptTcpClient(result);
ClientsList.Add(client);
StartMonitoring(); // repeats the monitoring
}
}
}
However, I'm having two issues with this code.
The first is the StartMonitoring()
call in HandleNewClient()
. Without it, the server will accept only one incoming connection and ignore any additional connections. What I'd like to do is have it continually monitor for new clients, but something rubs me wrong about the way I'm doing it now. Is there a better way of doing this?
The second is the _isMonitoring
flag. I don't know how else to stop the async callback from activating and stop it from looping. Any advice on how this can be improved? I'd like to stick to using asynchronous callbacks and avoid having to manually create new threads running methods that have while (true)
loops in them.