使用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();
}
}
关于.net - 如何在.NET中的线程上传播tcplistener传入连接?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62449/