hello,
i'm having the following problem with my application:
i need to check it for incomming tcp requests, but it get stuck if there aren't any of them. i need something to stop the loop after 5 seconds.
this is my code:
while (true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient(); <-- here it just waits till there is someone who wants to connect.
Console.WriteLine("Connected!");
}
how can i solve this??
i know i need to do somehing with the while but what??
thx!!
Nick
Loading
AlanPosted Nov 18, 2008, 2:26 PM
You can use the Pending() method to check whether there are any pending connection requests and thereby avoid blocking. You also need a timer to check whether the 5 seconds maximum wait has elapsed:
TcpClient client = null;
Console.Write("Waiting for a connection... ");
DateTime start = DateTime.Now;
while (true)
{
if (server.Pending())
{
client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
break;
}
else if ((DateTime.Now - start).TotalSeconds >= 5.0)
{
Console.WriteLine("Timed out after 5 seconds");
break;
}
}