从NetworkStream读取字节(挂起)

我正在尝试学习网络的基础知识,并且我已经从本教程中构建了一个echo服务器。 我用telnet检查了服务器,它完美无缺。

现在,当我在互联网上使用一些客户端样本时:

// 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行,一切都很完美(期望我无法阅读)。 我也试图以类似的方式使用异步回调方法来完成读取。 然后它只在我终止程序后工作(服务器处理请求)

我怀疑我从流中读取的方式导致了这个障碍,但是我太无能为力了解我做错了什么。

在没有数据可用的情况下,实现将阻塞,直到可以读取至少一个字节的数据。

来自MSDN

您的服务器可能不会向您发送任何数据。

编辑:

我测试了你的客户端,它运行得很好。 亲自尝试并设置以下参数:

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

这绝对是你的服务器有问题。