views:

39

answers:

1

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: 

Well, try it out - you will find that you get an IoException at one point if the client has disconnected. How long that takes - it may take a long time (if the diconnect is by meaans of network outage / power outage and the TCP stack has to wait for timeouts).

The "proper" way to end that is that the client sends an end command to the server, upon which the server disconnects the client. This allows the server to get rid of the client as fast as possible. Many internet protocols implement this, either implicit (HTTP - unless asked for different the server disconnects a client after sending the data) or explicit (SMTP - has a QUIT command the client is supposed to send to the server).

TomTom
My problem is like you said in the first part of your answer: becouse of a network problems, The client disconnected not as it should, so I can't sent a signal when it happend. Do you have another idea?
menacheb
No. YOu basically wait for the exception to happen. No other way.
TomTom
But as you said, it can take a long time. And I need to know, if not in the second it happend, then in the 2 minutes after.
menacheb
Then run regular traffic between client and server. I have a message based protocol between clients and servers in two cases, for example, where a ping is sent from both sides every second (to measure round trip time)
TomTom