TCP - 客户端在关闭后仍然保持打开状态

时间:2018-06-13 11:01:04

标签: c# tcpclient

我尝试使用TCP-Client和Server-Socket。我试图建立一个聊天室。

我发现即使我关闭了客户端tcp,连接的客户端也保持打开状态。我知道在MSDN描述中它说,只要仍然有数据要发送,TCP客户端仍然保持打开状态。但我等了20多分钟,客户才被关闭了。

为了让它更加清晰,我的服务器控制台代码是:

static void Main(string[] args)
    {
        List<TcpClient> allClients = new List<TcpClient>();
        TcpListener serverSocket = new TcpListener(IPAddress.Parse("127.0.0.1"), 8860);

        serverSocket.Start();
        Console.WriteLine("Server started");

        while (true)
        {
            TcpClient client = serverSocket.AcceptTcpClient();
            Console.WriteLine("Client connected");
            allClients.Add(client);
            Task.Run(() => 
            {
                HandleTCPClient(client);
            });
        }


        serverSocket.Stop();

        Console.WriteLine("Server is closed");
    }

    public static void HandleTCPClient(TcpClient client)
    {
        while (client.Connected)
        {
            try
            {
                NetworkStream data = client.GetStream();
                byte[] byteArray = new Byte[client.ReceiveBufferSize];
                if (data.DataAvailable)
                {
                    data.Read(byteArray, 0, client.ReceiveBufferSize);
                    String messageRaw = Encoding.UTF8.GetString(byteArray);
                    String message = messageRaw.Substring(0, messageRaw.IndexOf('|'));
                    Console.WriteLine(message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        Console.WriteLine("User disconnected");
        client.Close();
    }

这是我的客户端控制台代码:

static void Main(string[] args)
    {

        // Create the chat client for chatting with the server
        using (TcpClient chatClient = new TcpClient())
        {
            Console.WriteLine("Client Started");

            try
            {
                //try to connect to local host server with specific port
                chatClient.Connect(IPAddress.Parse("127.0.0.1"), 8860);
            }
            catch (Exception e)
            {
                Console.WriteLine("Server is not responding.");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("Client connected");
            Boolean exitLoop = false;

            //Loop while user inputs data
            using (NetworkStream clientDataStream = chatClient.GetStream())
            {
                do
                {
                    String input;
                    Console.Write("Wait for Input:");
                    input = Console.ReadLine();
                    if (input == "exit")
                        exitLoop = true;
                    else
                        sendMessage(clientDataStream, input);
                } while (!exitLoop);
            }
        }
    }

    /// <summary>
    /// Send the message to the server from the client
    /// </summary>
    /// <param name="client">Client which is sending the message</param>
    /// <param name="message">Message which will be send</param>
    static void sendMessage(NetworkStream networkStream, String message)
    {
        Byte[] messageByte = Encoding.UTF8.GetBytes(message + "|");
        networkStream.Write(messageByte, 0, messageByte.Length);
        Console.WriteLine("Message Send");
    }

我希望如果它关闭客户端 - TCP-Client,服务器控制台将输出“用户断开连接”。但客户端始终处于状态连接状态。

0 个答案:

没有答案