栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在.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());}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/402868.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号