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