我从TCP Asynchronous
服务器的世界开始,寻找一种同时处理多个连接的方法,我发现BeginAcceptTcpClient
可能是一种解决方案。
我发现了在服务器启动时使用BeginAcceptTcpClient
来接收连接的两种可能方法。我的问题是:这两者之间有什么区别,哪一个是线程安全的(或者两者都是)。
第一路
在回调中调用BeginAcceptTcpClient
。
static TcpListener socket = new TcpListener(IPAddress.Any, 4444);
public static void InitNetwork()
{
socket.Start();
socket.BeginAcceptTcpClient(new AsyncCallback(OnClientConnect), null);
}
private static void OnClientConnect(IAsyncResult ar)
{
TcpClient newclient = socket.EndAcceptTcpClient(ar);
socket.BeginAcceptTcpClient(new AsyncCallback (OnClientConnect), null); // Call the Callback again to continue listening
HandleClient.CreateConnection(newclient); //Do stuff with the client recieved
}
第二种方式
使用AutoResetEvent
。
static TcpListener socket = new TcpListener(IPAddress.Any, 4444);
private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);
public static void InitNetwork()
{
socket.Start();
while(true)
{
socket.BeginAcceptTcpClient(new AsyncCallback(OnClientConnect), null);
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 static void OnClientConnect(IAsyncResult ar)
{
TcpClient newclient = socket.EndAcceptTcpClient(ar);
connectionWaitHandle.Set(); //Inform the main thread this connection is now handled
HandleClient.CreateConnection(newclient); //Do stuff with the client recieved
}
我正在寻找处理多个连接的正确方法(成为线程安全的)。感谢您的回答。
答案 0 :(得分:0)
我更喜欢AcceptTcpClientAsync
。它比BeginAcceptTcpClient
更简单,并且仍然是异步的。
public async Task InitNetwork()
{
while( true )
{
TcpClient newclient = await socket.AcceptTcpClientAsync();
Task.Run( () => HandleClient.CreateConnection( newclient ) );
}
}
在内部,AcceptTcpClientAsync
使用Task.Factory.FromAsync
将BeginAcceptTcpClient
和EndAcceptTcpClient
包装到Task对象中。
public Task<TcpClient> AcceptTcpClientAsync()
{
return Task<TcpClient>.Factory.FromAsync(BeginAcceptTcpClient, EndAcceptTcpClient, null);
}