我使用,我用如何限制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