Is it possible to AcceptSocket
on a TcpListener
object with timeouts so that it is interrupted once in a while ?
TcpListener server = new TcpListener(localIP, port);
server.Start();
while (!shuttingDown)
try
{
Socket client = server.AcceptSocket();
if (client != null)
{
// do client stuff
}
}
catch { }
Trying BeginAccept and EndAccept: How do I end the accepting if there is no client like for 3 seconds ? (I'm trying to approximate the solution here)
server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), server);
Thread.Sleep(3000);
server.EndAcceptTcpClient(???);
I have created the following extension method as an overload for TcpListener.AcceptSocket which accepts a timeout parameter.
/// <summary>
/// Accepts a pending connection request.
/// </summary>
/// <param name="tcpListener"></param>
/// <param name="timeout"></param>
/// <param name="pollInterval"></param>
/// <exception cref="System.InvalidOperationException"></exception>
/// <exception cref="System.TimeoutException"></exception>
/// <returns></returns>
public static Socket AcceptSocket(this TcpListener tcpListener, TimeSpan timeout, int pollInterval=10)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
while (stopWatch.Elapsed < timeout)
{
if (tcpListener.Pending())
return tcpListener.AcceptSocket();
Thread.Sleep(pollInterval);
}
throw new TimeoutException();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With