Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout at AcceptSocket?

Tags:

c#

sockets

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(???);
like image 496
Bitterblue Avatar asked Oct 21 '22 21:10

Bitterblue


1 Answers

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();
    }
like image 165
Ryan Williams Avatar answered Oct 28 '22 15:10

Ryan Williams