是否有可能AcceptSocket
on a TcpListener
具有超时的对象,以便它偶尔被中断?
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(???);
我创建了以下扩展方法作为 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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)