2015-10-18 93 views
0

我正在使用此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();  

任何幫助,將不勝感激。

+1

既然你想連接到一個HTTP服務器,你爲什麼不使用[HttpClient的( https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx)而不是TcpClient? –

+2

您希望仔細閱讀['Stream.Read'](https://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx)方法的合同:*實現是免費的返回的字節數少於所請求的數量,即使流的末尾還沒有到達。* –

+0

您需要閱讀http協議,然後稍微好一點。例如,你應該閱讀行,直到你有所有的標題信息。然後,使用標題中指定的內容長度來讀取http響應的完整主體。這是我知道確定你已經找回所有東西的唯一途徑。在StreamReader中包裝你的流並使用ReadLine來開始。 – Lorek

回答

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

+0

不要像這樣解碼子字符串,這會弄亂編碼(想象多字節字符)。更好地將整個流複製到一個'MemoryStream'並且一次性解碼*。 –

+0

謝謝你的迴應,我認爲它應該做的伎倆,我會試一試,並會再次給你,再次感謝,Max – Max

+0

@LucasTrzesniewski感謝您的評論。我編輯了答案。 –

相關問題