【问题标题】:TCP Client reads first message but not the restTCP 客户端读取第一条消息但不读取其余消息
【发布时间】:2013-01-28 01:22:02
【问题描述】:

我正在尝试向现有服务器解决方案发送请求并写出结果。服务器总共发送了 4 条带有我的特定请求的消息,但返回的消息数量可能因初始查询而异。

我能够成功地将查询发送到服务器,但是在读取响应时,我只能读取一条消息。服务器日志显示有 4 个被退回。

请帮忙。

        IPHostEntry hostEntry = Dns.GetHostEntry(server_textbox.Text);
        IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], port);
        string data = String.Empty;
        testclient = new TcpClient(server_textbox.Text, port);
        testclient.ReceiveBufferSize = 1024;
        testclient.SendBufferSize = 1024;
        NetworkStream netStream = testclient.GetStream();
        Byte[] message_byte = new System.Text.ASCIIEncoding().GetBytes(msg2);
        netStream.Write(message_byte, 0, message_byte.Length);

        Byte[] returnMessage = new byte[1024];
        Int32 totalBytesReceived = 0;
        Int32 bytesReceived = 0;
        try
        {

            while ((bytesReceived = netStream.Read(returnMessage, totalBytesReceived, returnMessage.Length)) > 0)
            {
                totalBytesReceived += bytesReceived;
                data += "\n" + ASCIIEncoding.ASCII.GetString(returnMessage);

                bytesReceived = 0;
            }
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        result_box.Text += data;
        netStream.Close();
        testclient.Close();

    }

【问题讨论】:

  • Eric 打败了我,他说的。
  • 你发送多少字节?因为您将 totalBytesReceived 作为偏移量传递给 Read(),所以您将无法读取超过您指定为数组大小的 1024 个字节。
  • 1024 是我可以在服务器端接收硬编码的最大尺寸。

标签: c# tcpclient tcplistener


【解决方案1】:

我的猜测是,您的所有消息都在第一个Read 中读取。当服务器回复时,所有数据都被卡在 windows 接收缓冲区中,并被一次性读取。

我建议使用Wireshark,这在进行网络编程时或多或少是强制性的。您将能够看到从服务器返回的 4 条消息作为至少 4 个不同的 tcp 数据包。

【讨论】:

  • 我正在查看服务器发回的数据,我得到了一些非常奇怪的东西。我收到 3 条消息推送给我。前两条消息包含我所期望的,最后一条消息包含所有四条消息。
猜你喜欢
  • 2014-01-17
  • 2017-01-02
  • 2013-03-02
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 2015-10-08
  • 2016-04-15
  • 2017-12-20
相关资源
最近更新 更多