【发布时间】:2019-09-20 11:26:12
【问题描述】:
我从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
}
我正在寻找处理多个连接的正确方法(线程安全)。我很感激任何答案。
【问题讨论】:
标签: c# .net multithreading tcp