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事件處理程序編寫了代碼?不是你?更大的問題:爲什麼用戶想要點擊一個按鈕? –