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);
你怎么能不知道*你自己的代码*已经调用了Start()?重新考虑这一点。 –
@HansPassant:有一个用户界面。当用户单击Windows窗体上的“开始”按钮时会调用Start。 –
谁为Click事件处理程序编写了代码?不是你?更大的问题:为什么用户想要点击一个按钮? –