TCP客户端读取第一条消息但不读取其余消息

时间:2013-02-12 16:51:29

标签: c# tcpclient tcplistener

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

    }

1 个答案:

答案 0 :(得分:2)

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

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