AcceptSocket timeout?

Is it possible AcceptSocketin an object TcpListenerwith timeouts to interrupt after 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 can I end the reception if there is no client for 3 seconds? (I'm trying to approximate the solution here)

server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), server);
Thread.Sleep(3000);
server.EndAcceptTcpClient(???);
+4
source share
3 answers

This code checks for new clients establishing a connection. If so, it AcceptSocket()is called. The only problem is that the server has to check frequently to quickly respond to client requests.

TcpListener server = new TcpListener(localIP, port);
server.Start();
while (!shuttingDown)
{
    if (server.Pending())
    {
        Socket client = server.AcceptSocket();
        if (client != null)
        {
            // do client stuff
        }
    }
    else
        Thread.Sleep(1000);
}
0
source

I 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();
    }
+3

Just set the waiting time for reception in the listening jack. This calls accept () for the timeout in the same way as the read timeout, regardless of what is in C #.

0
source

All Articles