2011-04-18 101 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

相關問題