仅以 .net 套接字为例,我使用:
TcpListener listener = new TcpListener(ip, port);
while(true)
{
TcpClient client = socket.AcceptTcpClient();
DoSomethingWithClient(client);
}
但另一种方式似乎类似于(基于http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.beginaccepttcpclient.aspx):
public static ManualResetEvent tcpClientConnected = new ManualResetEvent(false);
public static void DoBeginAcceptTcpClient(TcpListener listener)
{
tcpClientConnected.Reset();
listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), listener);
tcpClientConnected.WaitOne();
}
public static void DoAcceptTcpClientCallback(IAsyncResult ar)
{
TcpListener listener = (TcpListener) ar.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(ar);
DoSomethingWithClient(client);
tcpClientConnected.Set();
}
恕我直言,异步风格需要 3 倍的代码,看起来像 goto spaghetti - 它难以阅读,并迫使您分离出相关代码。那么为什么要使用异步方式呢?想必它一定有什么优势吧?