I’m trying to implement a ping in my basic client-server chat. My problem is on the server side. I send the ping and then I want to wait up to 10 seconds for the client to ping me back. If the client doesn’t ping back after 10 seconds I want my while loop to break. Here is what I’ve done:
public void ping()
{
send("#PIN#");
bool ponged = false;
while (true)
{
string rec = receive(); // it blocks here !!!!!!!!!!
if (rec == "#PON#")
ponged = true;
}
}
There is no problem with my send() and receive() methods. They work fine everywhere else.
I tried using both a Stopwatch and a Timer to make the loop break after 10 seconds. The problem comes from the fact that the receive function blocks until a message has been received. Here is the part of the receive function that blocks:
bytesRead = clientStream.Read(byteMsg, 0, 4096);
As far as I know this is the proper way for receiving messages from my client. But of course if the client is disconnected, I will never get pinged back, which means my receive() method will never end. If my receive method never ends then my while loop never gets the opportunity to check stopWatch.Elapsed() or call an ElepsedEventHandler from a Timer.
So the question is, how can I force this while loop to break after 10 seconds knowing that one of the methods in that while loop is likely to not end?
Thank you for your time.
If you’re using a NetworkStream to read your data, there is a ReadTimeout property you can use.