3
我在想我是否正在构建一个应用程序。该应用程序必须接收传入的TCP连接,并为每个呼叫使用一个线程,以便服务器可以并行地应答多个呼叫。对于异步TCP侦听器,这种模式是否正确?
我正在做的事情就是尽快让我接受客户的电话BeginAcceptTcpClient
。我想,当ConnectionAccepted
方法被击中时,它实际上是在一个单独的线程中。
public class ServerExample:IDisposable
{
TcpListener _listener;
public ServerExample()
{
_listener = new TcpListener(IPAddress.Any, 10034);
_listener.Start();
_listener.BeginAcceptTcpClient(ConnectionAccepted,null);
}
private void ConnectionAccepted(IAsyncResult ia)
{
_listener.BeginAcceptTcpClient(ConnectionAccepted, null);
try
{
TcpClient client = _listener.EndAcceptTcpClient(ia);
// work with your client
// when this method ends, the poolthread is returned
// to the pool.
}
catch (Exception ex)
{
// handle or rethrow the exception
}
}
public void Dispose()
{
_listener.Stop();
}
}
我做对了吗?
干杯。
非常感谢! :) – vtortola 2011-04-21 10:06:47