2011-04-18 54 views
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(); 
    } 
} 

我做对了吗?

干杯。

回答

1

那么你可以使静态的方法是这样的:

private static void ConnectionAccepted(IAsyncResult ia) 
    {   
    var listener = (TcpListener)result.AsyncState; 
    TcpClient client = listener.EndAcceptTcpClient(); 
    listener.BeginAcceptTcpClient(ConnectionAccepted, listener); 
    // ..... 
    } 

也许你不希望它是静态的,但这种方式,您可以移动的方法,其中你喜欢它,不依赖于成员变量在这个班上,但另一个。 I.E:分离服务器tcp逻辑和服务器客户端逻辑。

+0

非常感谢! :) – vtortola 2011-04-21 10:06:47