简体   繁体   中英

How to know if the client call connection close on TcpListener?

I wrote simple application that using TcpListener. The application is wait till some client will connect - and while the client is connected the application will listen to his sending stream.

In the code - i using while loop to check if the client is connected. But event when i close the connection on the client side i get connected == true

But .. on the client close => i see that the server get byte stream with byte.length == 0

Code ...

private async void button1_Click(object sender, EventArgs e)
{
        TcpListener tcpListener = new TcpListener(IPAddress.Any, 5501);
        tcpListener.Start(1);       // listen one client only

        TcpClient client = await tcpListener.AcceptTcpClientAsync();

        NetworkStream networkStream = client.GetStream();

        while (client.Connected)    // after connected => this is always true .. event if i close the connection on the client side 
        {
            // do something ... 
        }

        System.Console.WriteLine("No Connected");
}

TCP is a connection- oriented protocol, but the connection still is a virtual one - the only way to know that the other party is still connected is by successfully sending or receiving a message to/from it. This is why the Connected property may give false positives.

The 0-byte message means that the client has sent all their data and has closed (the send direction of) the socket. At that point the client still is connected, waiting for a 0-byte message back from the server (which is automatically sent when you close the server socket).

Of course in case of a network failure you would never receive that 0-byte message, but you would receive (eventually) a SocketException instead.

See this WinSock FAQ for more information about the shutdown process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM