是否有一个属性/方法来确定TcpListener当前是否正在侦听

本文关键字:是否 TcpListener 属性 有一个 方法 | 更新日期: 2023-09-27 18:10:11

目前我正在做这样的事情:

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。服务器,因为如果它还没有启动,它也还没有被实例化。即使我可以访问它,我也不确定它是否包含一个Listening属性。

这真的是最好的方法吗?

是否有一个属性/方法来确定TcpListener当前是否正在侦听

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);

您可以直接从Socket获得此值。套接字总是在实例化TcpListener时创建的。

        if(tcpListener.Server.IsBound)
            // The TcpListener has been bound to a port
            // and is listening for new TCP connections