断开TCPClient并在另一端看到它

Sea*_*n P 2 .net c# sockets tcpclient disconnect

我试图断开客户端与服务器的连接,但服务器仍然将其视为已连接.我无法找到解决方案,关闭,断开和关闭所有不工作.

我与客户端断开连接并检查服务器的一些代码:

客户:

  private void btnDisconnect_Click(object sender, EventArgs e)
    {
        connTemp.Client.Shutdown(SocketShutdown.Both);
        connTemp.Client.Disconnect(false);
        connTemp.GetStream().Close();
        connTemp.Close();
    }
Run Code Online (Sandbox Code Playgroud)

服务器:

    while (client != null && client.Connected)
            {
                NetworkStream stream = client.GetStream();
                data = null;

                try
                {
                    if (stream.DataAvailable)
                    {
                        data = ReadStringFromClient(client, stream);
                        WriteToConsole("Received Command: " + data);
                    }
                } // So on and so on...
Run Code Online (Sandbox Code Playgroud)

代码中还有更多的写入和读取.

希望你们都能提供帮助.

更新:我甚至尝试通过ref传递TCP客户端,假设存在范围问题和client.Connected即使在读取后仍然为真.出了什么问题?

第二次更新!!:

这是解决方案.先查看并确定是否已连接.

  if (client.Client.Poll(0, SelectMode.SelectRead))
                    {
                        byte[] checkConn = new byte[1];
                        if (client.Client.Receive(checkConn, SocketFlags.Peek) == 0)
                        {
                            throw new IOException();
                        }
                    }
Run Code Online (Sandbox Code Playgroud)

Sea*_*n P 7

这是解决方案!!

  if (client.Client.Poll(0, SelectMode.SelectRead))
                {
                    byte[] checkConn = new byte[1];
                    if (client.Client.Receive(checkConn, SocketFlags.Peek) == 0)
                    {
                        throw new IOException();
                    }
                }
Run Code Online (Sandbox Code Playgroud)