I am creating a windows service that accepts TCP connections, processes data sent to the server, then returns back a message saying the process is complete. There are several clients that will be connecting to the service and that number is growing. To handle these messages, I thought that using a non-blocking structure would be ideal. From initial searches, the BeginAcceptTcpClient appeared to be what I was looking for. I was looking at this tutorial to get a sample, but I have a few questions on how this works. My code I have based on this example is below.
OnClientConnected function, why is it necessary to call WaitForClients again? Why doesn't the listener just always listen?WaitForClients is called again? I know it is the first statement in the OnClientConnected, but there could be two connections that happen "at the same time"OnClientConnected, then call WaitForClients, which will then allow another connection to be handled. This seems sort of a one connection at a time approach rather than having several threads that can handle lots of traffic.public class DeviceListener
{
private TcpListener listener = null;
public DeviceListener()
{
listener = new TcpListener(1001);
}
public void StartListener()
{
listener.Start();
//TODO: Log listening started here
WaitForClients();
}
private void WaitForClients()
{
listener.BeginAcceptTcpClient(OnClientConnected, null);
}
private void OnClientConnected(IAsyncResult asyncResult)
{
WaitForClients();
TcpClient client = listener.EndAcceptTcpClient(asyncResult);
if(client != null)
{
//TODO: Log connected
HandleClientRequest(client);
}
}
private void HandleClientRequest(TcpClient client)
{
//Code to process client request
}
}
BeginAcceptTcpClient calls, so in order to accept another one you need to call BeginAcceptTcpClient again. Beginning of handler seems like a reasonable place to do so.BeginAcceptTcpClient or timed out if that doesn't happen in timely manner.ThreadPool.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With