【问题标题】:Read bytes from NetworkStream (Hangs)从 NetworkStream 读取字节(挂起)
【发布时间】:2012-02-24 21:17:46
【问题描述】:

我正在尝试学习网络基础知识,并且我已经根据this 教程构建了一个回显服务器。我用 telnet 检查了服务器,它运行良好。

现在,当我使用 Internet 上的许多客户端示例时:

// 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 行,一切正常(希望我看不懂)。我也试图以类似的方式使用异步回调方法进行读取。然后它只在我终止程序后才起作用(服务器处理请求)

我怀疑我从流中读取的方式导致了这个块,但我太无能了,无法理解我做错了什么。

【问题讨论】:

  • 您确定服务器正在向您发送您可以阅读的内容吗?
  • 我无法通过调试来判断,但我看到了在 telnet 中打印回来的数据。我什至在服务器响应的末尾添加了“X”,以确保它是来自服务器的回复。
  • 回显服务器如何读取消息?您是否看到回显服务器何时收到消息并回复您上面的代码?
  • 您忘记了 client.Connect() 调用。
  • 也许回显服务器在发送回消息之前等待换行符\n?

标签: c# sockets networkstream


【解决方案1】:

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

来自MSDN

您的服务器可能没有向您发送任何数据。

编辑:

我测试了您的客户端,它运行良好。自己试试,设置如下参数:

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

肯定是你的服务器有问题。

【讨论】:

  • 它是一个回显服务器,它返回数据并且我能够使用 telnet 读取数据。我读取数据的方式一定有问题,因为它就在那里。
  • 尝试刷新你写的东西。回显服务器是否收到您的消息?
  • 忘记冲洗。 MSDN 声明:“Flush 方法实现了 Stream.Flush 方法;但是,由于 NetworkStream 没有缓冲,因此对网络流没有影响。”
  • 至于你的建议,我 stream.Flush();在写线之后,它也无济于事。如果我不想从流中读取,它肯定会起作用。所以我认为它总是获取数据,只要我试图阅读它就无法处理某些东西。但话又说回来,使用 telnet 一切正常......
猜你喜欢
  • 2017-06-24
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 2019-12-02
  • 2021-03-23
  • 2016-06-29
  • 2015-01-28
  • 2011-05-07
相关资源
最近更新 更多