C# TCP客户端没有';在某些计算机上,我看不到所有的响应

C# TCP客户端没有';在某些计算机上,我看不到所有的响应,c#,C#,我使用这个MS示例代码从Apache服务器读取响应,但在某些计算机上,C#app只读取HTTP头,不读取正文。例如,如果我将“Hello”放在我的索引页上,它只读取包括HTTP/1.1200 OK DATE在内的标题: 不包括我在索引页中输入的内容 我试图增加数据的大小,但没有区别 TcpClient client = new TcpClient(server, port); // Translate the passed message into ASCII and store it as

我使用这个MS示例代码从Apache服务器读取响应,但在某些计算机上,C#app只读取HTTP头,不读取正文。例如,如果我将“Hello”放在我的索引页上,它只读取包括HTTP/1.1200 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();     

任何帮助都将不胜感激。

读取
方法可以在读取部分响应后返回。您必须循环并将数据复制到
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服务器,您可以使用

,因为您想连接到http服务器,为什么不使用而不是TcpClient?您应该仔细阅读该方法的约定:即使未到达流的结尾,实现也可以自由返回比请求更少的字节。您可能希望了解http协议,然后更好地实现它。例如,您应该阅读行,直到您拥有所有的标题信息。然后,使用标头中指定的内容长度来读取http响应的全文。这是我唯一能确定你已经找回一切的方法。在StreamReader中包装您的流,并使用ReadLine开始工作;s建议并使用Http客户端。这将为您完成http任务。例如,我认为仅在第一部分返回报头被认为是tcp/ip层的标准实践。http客户机处理了大量您刚刚开始使用的功能。不要这样解码子字符串,这可能会弄乱编码(想想多字节字符)。最好将整个流复制到一个
内存流
中,并在一次传递中解码。感谢您的回复,我认为它应该可以做到这一点,我会尝试一下,然后再给您回复,再次感谢,Max@LucasTrzesniewski谢谢你的评论。我编辑了答案。@JakubLortz C#说不能将其分配给responseData。无论如何,这个解决方案对我来说是可行的,非常感谢:)顺便说一句,由于某些原因,我无法使用httpClient来满足我的需要。