2011-10-03 78 views
9

目前我在做這樣的事情:是否有確定TcpListener當前正在偵聽的屬性/方法?

public void StartListening() 
{ 
    if (!isListening) 
    { 
     Task.Factory.StartNew(ListenForClients); 

     isListening = true; 
    } 
} 

public void StopListening() 
{ 
    if (isListening) 
    { 
     tcpListener.Stop(); 

     isListening = false; 
    } 
} 

請問有沒有方法或屬性中的TcpListener,以確定是否已經的TcpListener開始聽(即TcpListener.Start()被調用)?無法真正訪問TcpListener.Server,因爲如果它尚未啓動,它還沒有被實例化。即使我可以訪問它,我也不確定它是否包含Listening屬性。

這真的是最好的方法嗎?

+0

你怎麼能不知道*你自己的代碼*已經調用了Start()?重新考慮這一點。 –

+0

@HansPassant:有一個用戶界面。當用戶單擊Windows窗體上的「開始」按鈕時會調用Start。 –

+0

誰爲Click事件處理程序編寫了代碼?不是你?更大的問題:爲什麼用戶想要點擊一個按鈕? –

回答

18

TcpListener實際上有一個名爲Active的屬性,它正是你想要的。但是,由於某種原因,該屬性被標記爲受保護,因此除非從TcpListener類繼承,否則無法訪問它。

您可以通過在項目中添加一個簡單的包裝來解決此限制。

/// <summary> 
/// Wrapper around TcpListener that exposes the Active property 
/// </summary> 
public class TcpListenerEx : TcpListener 
{ 
    /// <summary> 
    /// Initializes a new instance of the <see cref="T:System.Net.Sockets.TcpListener"/> class with the specified local endpoint. 
    /// </summary> 
    /// <param name="localEP">An <see cref="T:System.Net.IPEndPoint"/> that represents the local endpoint to which to bind the listener <see cref="T:System.Net.Sockets.Socket"/>. </param><exception cref="T:System.ArgumentNullException"><paramref name="localEP"/> is null. </exception> 
    public TcpListenerEx(IPEndPoint localEP) : base(localEP) 
    { 
    } 

    /// <summary> 
    /// Initializes a new instance of the <see cref="T:System.Net.Sockets.TcpListener"/> class that listens for incoming connection attempts on the specified local IP address and port number. 
    /// </summary> 
    /// <param name="localaddr">An <see cref="T:System.Net.IPAddress"/> that represents the local IP address. </param><param name="port">The port on which to listen for incoming connection attempts. </param><exception cref="T:System.ArgumentNullException"><paramref name="localaddr"/> is null. </exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="port"/> is not between <see cref="F:System.Net.IPEndPoint.MinPort"/> and <see cref="F:System.Net.IPEndPoint.MaxPort"/>. </exception> 
    public TcpListenerEx(IPAddress localaddr, int port) : base(localaddr, port) 
    { 
    } 

    public new bool Active 
    { 
     get { return base.Active; } 
    } 
} 

你可以用它來代替任何TcpListener對象。

TcpListenerEx tcpListener = new TcpListenerEx(localaddr, port); 
相關問題