TcpListener thực sự có thuộc tính được gọi là Hoạt động thực hiện chính xác những gì bạn muốn. Tuy nhiên, thuộc tính được đánh dấu được bảo vệ vì một số lý do để bạn không thể truy cập nó trừ khi bạn kế thừa từ lớp TcpListener.
Bạn có thể vượt qua giới hạn này bằng cách thêm trình bao bọc đơn giản vào dự án của bạn.
/// <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; }
}
}
Mà bạn có thể sử dụng thay cho đối tượng TcpListener bất kỳ.
TcpListenerEx tcpListener = new TcpListenerEx(localaddr, port);
Nguồn
2011-10-22 06:30:03
Làm thế nào bạn có thể không biết rằng * mã của riêng bạn * đã gọi là Start()? Đừng nghĩ lại điều này một chút. –
@HansPassant: Có giao diện người dùng. Bắt đầu được gọi khi người dùng nhấp vào nút Bắt đầu trên biểu mẫu cửa sổ. –
Ai đã viết mã cho trình xử lý sự kiện Click? Không phải bạn? Câu hỏi lớn hơn: tại sao người dùng muốn nhấp vào nút? –