开发者

How to know when the Client is disconnected from Server in C#?

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);
             dataFromClien开发者_运维问答t = 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,


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜