使用Net.Sockets.TcpListener时,在单独的线程中处理传入连接(.AcceptSocket)的最佳方法是什么?
我们的想法是在接受新的传入连接时启动一个新线程,然后tcplistener保持可用于进一步的传入连接(并且为每个新的传入连接创建一个新线程).与发起连接的客户端的所有通信和终止都将在线程中处理.
示例C#VB.NET代码表示赞赏.
我一直在使用的代码如下所示:
class Server { private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false); public void Start() { TcpListener listener = new TcpListener(IPAddress.Any, 5555); listener.Start(); while(true) { IAsyncResult result = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener); connectionWaitHandle.WaitOne(); // Wait until a client has begun handling an event connectionWaitHandle.Reset(); // Reset wait handle or the loop goes as fast as it can (after first request) } } private void HandleAsyncConnection(IAsyncResult result) { TcpListener listener = (TcpListener)result.AsyncState; TcpClient client = listener.EndAcceptTcpClient(result); connectionWaitHandle.Set(); //Inform the main thread this connection is now handled //... Use your TcpClient here client.Close(); } }