从NetworkStream中读取字节(挂起)
问题描述:
我在学习网络基础知识,并从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行,一切工作完美(期望我不能读)。我也试图以类似的方式使用异步回调方法进行读取。然后它只在我终止程序(服务器处理请求)后才起作用(服务器处理请求)
我怀疑我从流中读取的方式会导致此块,但我太无知,无法理解我在做什么错误。
答
该实现将阻塞,直到至少有一个字节的数据可以是 读取,如果没有数据可用的话。
从MSDN
您的服务器propably不发送任何数据。
编辑:
我测试你的客户和它的作品完美的罚款。尝试一下,并设置以下参数:
string server = "google.com";
int port = 80;
string message = "GET /\n";
这绝对是你的服务器有问题。
确定服务器正在向您发送您可以阅读的内容吗? – dtb 2012-02-24 13:01:02
我不能说槽调试,但我看到数据打印回telnet。我甚至在服务器响应的末尾添加了“X”,以确保它是来自服务器的回复。 – 2012-02-24 13:04:40
回应服务器如何读取消息?你看到回显服务器何时收到消息并回复上面的代码吗? – BlueM 2012-02-24 13:11:26