2009-08-25 37 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