我使用,我用如何限制TcpClient等待连接或客户端的特定时间而不是停止接受客户端?
TcpClient c = t.AcceptTcpClient();
一个简单的客户端交互现在无限期地等待客户端register.Now我要的是它等待比方说5分钟,然后自动停止听
我使用,我用如何限制TcpClient等待连接或客户端的特定时间而不是停止接受客户端?
TcpClient c = t.AcceptTcpClient();
一个简单的客户端交互现在无限期地等待客户端register.Now我要的是它等待比方说5分钟,然后自动停止听
只需使用TcpListener
的Pending
方法即可。 喜欢的东西
private TcpClient TryToConnect() {
DateTime dtStart=DateTime.Now;
while(CheckTime(dtStart)) {
if(t.Pending()) { return(t.AcceptTcpClient()); } //someone wants to connect
//maybe it's a good idea to give some resources to other processes
Thread.Sleep(100);
}
//no one came in here
return(null);
}
CheckTime(DateTime p)
- 是一个方法(你必须写),检查DateTime.Now
反对参数。如果有剩余时间返回true
- 否则返回false
。
假设你正在使用Windows服务,你可以使用一个计时器:
System.Timers.Timer myTimer;
在服务的的OnStart事件:
protected override void OnStart(string[] args)
{
MyListener.StartListening();
myTimer.Start();
}
在定时器的经过事件:
private void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
MyListener.StopListening();
myTimer.Stop();
}
这可能会满足您的直接需求,但我也建议看看Threading。
*编辑:同样的原理适用于使用Timer与Winforms。
请注意,如果在Listener上调用Stop而AcceptTcpClient仍然阻塞,则对AcceptTcpClient的调用将抛出SocketException。 – 2009-08-25 19:08:33