views:

52

answers:

2

I am using a simple client interaction in which i use

TcpClient c = t.AcceptTcpClient();

now it waits indefinately for a client to register.Now what i want is it wait for say 5 mins and then automatically stop to listen

A: 

Simply use the Pending method of the TcpListener. Something like

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) - is a method (you have to write) which checks DateTime.Now against the parameter. If there is time left return true - else return false.

ManniAT
+1  A: 

Assuming you're using a Windows Service, you could use a Timer:

System.Timers.Timer myTimer;

In your service's OnStart event:

protected override void OnStart(string[] args)
{
    MyListener.StartListening();
    myTimer.Start();
}

In the Timer's Elapsed event:

private void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    MyListener.StopListening();
    myTimer.Stop();
}

This might fullfill your immediate needs, but I'd also suggest having a look at Threading.

*Edit: The same principle applies using a Timer with Winforms.

Mr. Smith
Note that the call to AcceptTcpClient will throw a SocketException if you call Stop on the Listener while AcceptTcpClient is still blocking.
Adam Hughes