5

是否可以AcceptSocketTcpListener具有超时的对象进行一次中断?

TcpListener server = new TcpListener(localIP, port);
server.Start();
while (!shuttingDown)
    try
    {
        Socket client = server.AcceptSocket();
        if (client != null)
        {
            // do client stuff
        }
    }
    catch { }

尝试 BeginAccept 和 EndAccept:如果 3 秒内没有客户端,我该如何结束接受?(我试图在这里近似解决方案)

server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), server);
Thread.Sleep(3000);
server.EndAcceptTcpClient(???);
4

3 回答 3

3

我创建了以下扩展方法作为 TcpListener.AcceptSocket 的重载,它接受超时参数。

    /// <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();
    }
于 2015-03-17T03:29:06.803 回答
0

此代码检查是否有新客户端建立连接。如果AcceptSocket()是这样的话。唯一的问题是服务器必须经常检查以快速响应客户端。

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);
}
于 2013-10-29T10:35:52.573 回答
0

只需在侦听套接字上设置读取超时。这会导致accept()超时,就像发生读取超时一样,无论在 C# 中是什么。

于 2013-10-29T22:26:53.350 回答