0

我正在尝试向现有服务器解决方案发送请求并写出结果。服务器总共发送了 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();

    }
4

1 回答 1

2

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

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

于 2013-02-12T16:55:51.583 回答