2011-10-03 8 views
9

Actualmente estoy haciendo algo como esto:¿Existe una propiedad/método para determinar si un TcpListener está escuchando actualmente?

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

     isListening = true; 
    } 
} 

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

     isListening = false; 
    } 
} 

¿No hay un método o propiedad dentro de TcpListener para determinar si un TcpListener ha comenzado a escuchar (es decir TcpListener.Start() se llamaba)? Realmente no puedo acceder a TcpListener.Server porque si aún no se ha iniciado, aún no se ha instanciado. Incluso si pudiera acceder a él, no estoy seguro de que incluso contenga una propiedad de Escucha.

¿Es esta la mejor manera?

+0

¿Cómo no puede saber que * su propio código * ha llamado a Start()? Re-piensa esto un poco. –

+0

@HansPassant: hay una interfaz de usuario. Se invoca el inicio cuando el usuario hace clic en el botón Inicio en el formulario de Windows. –

+0

¿Quién escribió el código para el controlador de eventos Click? ¿No tú? Pregunta más importante: ¿por qué querría el usuario hacer clic en un botón? –

Respuesta

18

El TcpListener actualmente tiene una propiedad llamada Activo que hace exactamente lo que usted desea. Sin embargo, la propiedad está marcada como protegida por algún motivo, por lo que no puede acceder a ella a menos que herede de la clase TcpListener.

Puede evitar esta limitación agregando un envoltorio simple a su proyecto.

/// <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; } 
    } 
} 

Que puede utilizar en lugar de cualquier objeto TcpListener.

TcpListenerEx tcpListener = new TcpListenerEx(localaddr, port); 
Cuestiones relacionadas