我正在使用此MS示例代码从我的Apache服务器读取响应,但在某些计算机上,C#应用程序只读取HTTP HEADER并且不读取正文。例如,如果我在索引页面上放置“Hello”,它只会读取包含HTTP / 1.1 200 OK DATE的标题:......
不包括我在索引页面中放置的内容。
我试图增加数据的大小,但没有区别。
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
任何帮助都将不胜感激。
答案 0 :(得分:0)
在阅读部分响应后,Read
方法可以返回。您必须循环并将数据复制到MemoryStream
,直到无法接收更多数据。然后解码整个消息。
MemoryStream memoryStream = new MemoryStream();
Int32 bytes = 0;
do
{
bytes = stream.Read(data, 0, data.Length);
memoryStream.Write(data, 0, bytes);
}
while (stream.DataAvailable);
responseData = Encoding.ASCII.GetString(memoryStream.ToArray());
正如@YacoubMassad在评论中注意到的,如果你连接到http服务器,你可以使用HttpClient