2012-02-24 79 views
1

我在學習網絡基礎知識,並從this教程構建了一個回顯服務器。我用telnet檢查服務器,它的工作原理非常完美。從NetworkStream中讀取字節(掛起)

現在,當我使用了一些互聯網上的許多客戶端的樣本:

// Create a TcpClient. 
// Note, for this client to work you need to have a TcpServer 
// connected to the same address as specified by the server, port 
// combination. 
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. 
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(); 

它沒有很好地工作。如果我將評論stream.Read行,一切工作完美(期望我不能讀)。我也試圖以類似的方式使用異步回調方法進行讀取。然後它只在我終止程序(服務器處理請求)後才起作用(服務器處理請求)

我懷疑我從流中讀取的方式會導致此塊,但我太無知,無法理解我在做什麼錯誤。

+0

確定服務器正在向您發送您可以閱讀的內容嗎? – dtb 2012-02-24 13:01:02

+0

我不能說槽調試,但我看到數據打印回telnet。我甚至在服務器響應的末尾添加了「X」,以確保它是來自服務器的回覆。 – 2012-02-24 13:04:40

+0

迴應服務器如何讀取消息?你看到回顯服務器何時收到消息並回覆上面的代碼嗎? – BlueM 2012-02-24 13:11:26

回答

1

該實現將阻塞,直到至少有一個字節的數據可以是 讀取,如果沒有數據可用的話。

MSDN

您的服務器propably不發送任何數據。

編輯:

我測試你的客戶和它的作品完美的罰款。嘗試一下,並設置以下參數:

string server = "google.com"; 
    int port = 80; 
    string message = "GET /\n"; 

這絕對是你的服務器有問題。

+0

這是一個回聲服務器,它的劑量返回數據,我可以用telnet讀取數據。我閱讀數據的方式必須存在一些問題,因爲它在那裏。 – 2012-02-24 13:03:16

+0

嘗試沖洗你寫的東西。回聲服務器是否收到您的消息? – BlueM 2012-02-24 13:06:34

+0

忘掉沖洗。 MSDN指出:「Flush方法實現Stream.Flush方法;但是,由於NetworkStream沒有被緩衝,所以它不會影響網絡流。」 – BlueM 2012-02-24 13:10:20