2009-08-25 38 views

回答

0

只需使用TcpListenerPending方法即可。 喜歡的東西

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

1

假設你正在使用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。

+0

請注意,如果在Listener上調用Stop而AcceptTcpClient仍然阻塞,則對AcceptTcpClient的調用將拋出SocketException。 – 2009-08-25 19:08:33