TcpListener aslında tam olarak istediğiniz şeyi yapan Active adlı bir özelliğe sahiptir. Ancak, özellik TcpListener sınıfından devralmadıkça erişemeyeceğiniz için, bir nedenle korunur.
Projenize basit bir sarıcı ekleyerek bu sınırlamayı aşabilirsiniz.
/// <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; }
}
}
Herhangi bir TcpListener nesnesinin yerine kullanabilirsiniz.
TcpListenerEx tcpListener = new TcpListenerEx(localaddr, port);
Kendi kodunuzun * Start() adını verdiğini nasıl bilemezsiniz? Bunu biraz düşün. –
@HansPassant: Bir kullanıcı arayüzü var. Kullanıcı, Windows formundaki Başlat düğmesine tıkladığında başlatılır. –
Click olay işleyicisinin kodunu kim yazdı? Sen değil? Daha büyük soru: Kullanıcı neden bir düğmeyi tıklamak ister? –