您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在.NET中从NetworkStream读取的正确方法是什么

在.NET中从NetworkStream读取的正确方法是什么

设置底层套接ReceiveTimeout属性就可以了。您可以像这样访问它:yourTcpClient.Client.ReceiveTimeout。您可以阅读文档获取更多信息。

现在,只要某些数据到达套接字,该代码将仅“hibernate”,否则,如果在读取操作开始时超过20ms,如果没有数据到达,它将引发异常。如果需要,我可以调整此超时时间。现在,我不必为每次迭代付出20毫秒的代价,而只是在最后一次读取操作时才付出代价。因为我在从服务器读取的第一个字节中具有消息的内容长度,所以我可以使用它来进一步调整它,并且如果已经收到所有期望的数据,则不尝试读取。

我发现使用ReceiveTimeout比实现异步读取要容易得多…这是工作代码

string SendCmd(string cmd, string ip, int port)
{
  var client = new TcpClient(ip, port);
  var data = Encoding.GetEncoding(1252).GetBytes(cmd);
  var stm = client.GetStream();
  stm.Write(data, 0, data.Length);
  byte[] resp = new byte[2048];
  var memStream = new MemoryStream();
  var bytes = 0;
  client.Client.ReceiveTimeout = 20;
  do
  {
      try
      {
          bytes = stm.Read(resp, 0, resp.Length);
          memStream.Write(resp, 0, bytes);
      }
      catch (IOException ex)
      {
          // if the ReceiveTimeout is reached an IOException will be raised...
          // with an InnerException of type SocketException and ErrorCode 10060
          var socketExept = ex.InnerException as SocketException;
          if (socketExept == null || socketExept.ErrorCode != 10060)
              // if it's not the "expected" exception, let's not hide the error
              throw ex;
          // if it is the receive timeout, then reading ended
          bytes = 0;
      }
  } while (bytes > 0);
  return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
dotnet 2022/1/1 18:23:53 有533人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶