目前我正在做这样的事情:
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 :(得分:24)
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);
答案 1 :(得分:0)
您可以直接从套接字获取此信息。始终在实例化TcpListener时创建一个Socket。
if(tcpListener.Server.IsBound)
// The TcpListener has been bound to a port
// and is listening for new TCP connections