views:

59

answers:

3

Hi,
I have a Client-Server program in C#.
Here is the Server's code:

...
String dataFromClient =  "";
NetworkStream networkStream;
TcpClient clientSocket;
bool transfer = true;
...
while (transfer)
    {

         networkStream = clientSocket.GetStream();
         networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
         dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
         dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
         ....
     }

I want to make a condition that stop the loop when the Client is disconnected.
How can I do that?
Many thanks,

A: 

Have a look at the .Connected property of ClientSocket

Edit:

There is a discussion on this here and here which is probably a better place for this question anyway.

Iain
Yes, but my problem is the the clients are disconnected becouse of a network problem.
Regardless of why the client is disconnecting the question is quite clearly about a programming problem and is therefore on the wrong site.
A: 

It is impossible without trying to send some data.

There was a good discussion about it on stackoverflow, but I can't seem to be able to find it now...

Kalmi
+2  A: 

It is indeed impossible to detect this directly. You can only try to minimize the 'damage'.

Why is it impossible?

Because the TCP stream does not send any data to check if the connection still exists (that would cause unwanted overhead for little benefit). You have to initiate such checks manually. A simple idea is to ping regularly to see if the connection is still working.

How should I handle this?

Always check the Connected property before attempting to read/write. This is not more than a simple sanity check, the Connected state is always outdated (this is due to its nature explained above, no way to change this).

In any case, you still need to handle connection exceptions always - it is impossible to guarantee that a transmission will be successful, you can only try to avoid writing if the connection is already lost.

If you noticed a failed transmission, you have to deal with it in some way. You can cache the data and try to reconnect, then send again. Or you can ignore the failed transmission. It depends on your specific requirements.

mafutrct