Question

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(???);
Était-ce utile?

La solution 2

This code checks if there are new clients establishing a connection. If so AcceptSocket() is called. The only problem is server must check often for a quick respond to clients.

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);
}

Autres conseils

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

Just set a read timeout on the listening socket. That causes accept() to timeout in the same way that a read timeout happens, whatever that is in C#.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top