c# - TCPClient收不到数据

标签 c# tcpclient

我想使用 StreamReader 和 StreamWriter 通过 TCPClient.NetworkStream 接收和发送数据。代码如下所示:
客户端代码:

 using (TcpClient client = new TcpClient())
            {
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9001);
                client.Connect(localEndPoint);
                client.NoDelay = true;

                using(NetworkStream stream = client.GetStream())
                {                    
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        writer.AutoFlush = true;
                        using (StreamReader reader = new StreamReader(stream))
                        {    

                            string message = "Client says: Hello";
                            writer.WriteLine(message);

                // If I comment the line below, the server receives the  first message
                // otherwise it keeps waiting for data
                           string response = reader.ReadToEnd();
                           Console.WriteLine(response);
                        }
                       ;
                    }
                }
            }


注意:如果我评论 reader.ReadToEnd();然后服务器接收消息,否则服务器一直等待来自客户端的数据。 ReadToEnd 是问题所在吗?

服务器代码异步接受连接,但以同步方式处理数据:

class Program
    {
        private static AsyncCallback tcpClientCallback;
        static void Main(string[] args){

            IPEndPoint localEndPoint =  new IPEndPoint(IPAddress.Parse("127.0.0.1"),9001);
            TcpListener listener = new TcpListener(localEndPoint);

            listener.Start();

            tcpClientCallback = new AsyncCallback(ConnectCallback);
            AcceptConnectionsAysnc(listener);

            Console.WriteLine("Started Aysnc TCP listener, press any key to exit (server is free to do other tasks)");
            Console.ReadLine();
        }

        private static void AcceptConnectionsAysnc(TcpListener listener)
        {
            listener.BeginAcceptTcpClient(tcpClientCallback, listener);
        }

        static void ConnectCallback(IAsyncResult result)
        {
            Console.WriteLine("Received a conenct request");
            TcpListener listener = (TcpListener)result.AsyncState;

            // We are starting a thread which waits to receive the data
            // This is not exactly scalable
            Task recieveTask = new Task(() => { HandleRecieve(result, listener); });
            recieveTask.Start();

            AcceptConnectionsAysnc(listener);
        }


        // This makes a blocking call - that means until the client is ready to
        // send some data the server waits
        private static void HandleRecieve(IAsyncResult result, TcpListener listener)
        {
            Console.WriteLine("Waiting for data");

            using (TcpClient client = listener.EndAcceptTcpClient(result))
            {
                client.NoDelay = true;

                using (NetworkStream stream = client.GetStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.AutoFlush = true;
                            Stopwatch watch = new Stopwatch();
                            watch.Start();
                            string data = reader.ReadToEnd();
                            watch.Stop();
                            Console.WriteLine("Time: " + watch.Elapsed.TotalSeconds);
                            Console.WriteLine(data);


// Send a response to client
                                writer.WriteLine("Response: " + data);
                            }

                        }
                    }            


                }

            }

        } 

最佳答案

流在关闭之前不会结束。目前,客户端和服务器都保持连接打开,并且都试图从对方读取到最后 - 当它们这样做时,将关闭自己。这是一个僵局:两者都不会到达终点,因此也永远不会关闭(这将允许另一个到达终点)。

选项:

  • 使用原始套接字,并让客户端在发送后关闭出站流:

    socket.Shutdown(SocketShutdown.Send);
    

    这让服务器读取完成,这让服务器关闭,让客户端读取完成;关闭出站套接字后,客户端仍然可以从入站流中读取数据。

  • 使用与ReadToEnd 不同的终止隐喻;对于基于文本的协议(protocol),行尾是最常见的(因此:ReadLine);对于二进制协议(protocol),消息的长度前缀是最常见的。这允许每一端读取下一条消息,而不必读取到流的末尾。在这种情况下,它只会一条消息,但该策略仍然有效。

  • 如果您发现上述问题很棘手,请使用不同的协议(protocol); http 适用于单个请求/响应操作,并且可以通过 HttpListener 在服务器上进行处理。

此外,我会非常小心地在服务器上使用 ReadToEnd(甚至是 ReadLine)——这可能是在服务器上锁定线程的好方法.如果服务器需要处理高吞吐量和大量连接,则首选基于原始套接字的异步 IO。

关于c# - TCPClient收不到数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13134458/

相关文章:

c# - 如何使用Observablecollection制作列表数据以显示在列表框中

c# - 以编程方式检查 MSI 的产品版本

c# - TcpClient.GetStream().DataAvailable 返回 false,但流有更多数据

c# - MySQL、EF6 和 Database.CreateIfNotExists

c# - 使用 XmlDocument 遍历 XML

c# - 如何检查windowsstore应用程序中是否存在文件

c# - TCPClient没有网卡能用吗?

java - 当 Activity 发生变化时,如何保持与服务器的 TCP 连接?

c++ - TCP Telnet 传输中丢失字符

.net - VB.NET 使用 system.net.tcpclient 编写 telnet 客户端