我在學習網絡基礎知識,並從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行,一切工作完美(期望我不能讀)。我也試圖以類似的方式使用異步回調方法進行讀取。然後它只在我終止程序(服務器處理請求)後才起作用(服務器處理請求)
我懷疑我從流中讀取的方式會導致此塊,但我太無知,無法理解我在做什麼錯誤。
確定服務器正在向您發送您可以閱讀的內容嗎? – dtb 2012-02-24 13:01:02
我不能說槽調試,但我看到數據打印回telnet。我甚至在服務器響應的末尾添加了「X」,以確保它是來自服務器的回覆。 – 2012-02-24 13:04:40
迴應服務器如何讀取消息?你看到回顯服務器何時收到消息並回覆上面的代碼嗎? – BlueM 2012-02-24 13:11:26