AcceptSocket
对象的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(???);
答案 0 :(得分: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();
}
答案 1 :(得分: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);
}
答案 2 :(得分:0)
只需在侦听套接字上设置接收超时。这会导致accept()超时,就像发生读取超时一样,无论C#中是什么。