2011-10-03 77 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); 
相关问题