我正在使用此MS示例代碼來讀取來自我的Apache服務器的響應,但在某些計算機上,C#應用程序只是讀取HTTP頭文件而不會讀取正文。例如,如果我在索引頁上放置了「Hello」,它只會讀取包含HTTP/1.1的標頭200 OK日期:......TCP客戶端不會讀取某些計算機上的所有響應
不包括我在索引頁中放置的內容。
我試圖增加數據的大小,但沒有區別。
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();
任何幫助,將不勝感激。
既然你想連接到一個HTTP服務器,你爲什麼不使用[HttpClient的( https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx)而不是TcpClient? –
您希望仔細閱讀['Stream.Read'](https://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx)方法的合同:*實現是免費的返回的字節數少於所請求的數量,即使流的末尾還沒有到達。* –
您需要閱讀http協議,然後稍微好一點。例如,你應該閱讀行,直到你有所有的標題信息。然後,使用標題中指定的內容長度來讀取http響應的完整主體。這是我知道確定你已經找回所有東西的唯一途徑。在StreamReader中包裝你的流並使用ReadLine來開始。 – Lorek