加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – NetworkStream获取System.IO.IOException:无法将数据写入

发布时间:2020-12-16 01:26:21 所属栏目:百科 来源:网络整理
导读:我正在使用NetworkStream来保持可以发送消息的开放TCP / IP连接.我收到一条消息,处理它,然后返回一个ACK.我正在使用一个偶尔收到消息的站点,但是当我发送ACK时,我得到一个IOException.有时这只持续一两条消息(我可以接收下一条消息),有时它会一直持续到服务
我正在使用NetworkStream来保持可以发送消息的开放TCP / IP连接.我收到一条消息,处理它,然后返回一个ACK.我正在使用一个偶尔收到消息的站点,但是当我发送ACK时,我得到一个IOException.有时这只持续一两条消息(我可以接收下一条消息),有时它会一直持续到服务停止并重新启动.

下面是我的NetworkStream的代码,没有任何处理:

using (NetworkStream stream = client.GetStream())
{
   stream.ReadTimeout = ReadTimeout;
...
   if (stream.CanRead && stream.DataAvailable)
   bytesRead = stream.Read(receivedBytes,BufferSize);
...
   stream.Write(ack,ack.Length);
}

请注意,代码在读取新消息和发送ACK之间循环.

当我调用stream.Write时,我有时会得到以下异常:

System.IO.IOException: Unable to write data to the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine
   at System.Net.Sockets.NetworkStream.Write(Byte[] buffer,Int32 offset,Int32 size)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Write(Byte[] buffer,Int32 size)
   at Framework.Communication.Model.Server.AcceptMessage(IAsyncResult ar)

我看了这个消息,并为几种不同的通信方法找到了几个sources.听起来这是一个非常通用的例外,并不能真正说明发生了什么.

有谁知道会导致这种情况,或者我可以开始寻求缩小解决方案的范围?

解决方法

你认为这是一个普遍的问题是正确的,所以你必须更加防守.

要考虑的事情

>当应用程序以正确的方式关闭套接字时,它会发送包含0个字节的消息.
>在某些情况下,您可能会收到SocketException,表明出现了问题.
>在第三种情况下,远程方不再连接(例如通过拔下网络电缆),而双方之间没有任何通信.

>如果发生这种情况,您必须将数据写入套接字,以便检测到您无法再访问远程方.这就是发明保持活动机制的原因 – 它们经常检查它们是否仍能与另一方通信.

Note : None of this explains the intermittent nature of part of the
question (if i’m reading it correctly)

所以让我们看一下文档说的内容

NetworkStream.Write Method (Byte[],?Int32,?Int32)

IOException

  • There was a failure while writing to the network.
  • An error occurred when accessing the socket. See the Remarks section for more information.

Remarks

If you receive a SocketException,use the
SocketException.ErrorCode property to obtain the specific error
code,and refer to the Windows Sockets version 2 API error code
documentation in MSDN for a detailed description of the error
.

所以在我看来,如前所述,你需要更加防守.

>检查0个字节.
>检查错误.

>我收到错误,请确保您正在检查错误代码

在其中任何一种情况下,重新启动连接,记录故障并假设连接已关闭(或异常关闭)可能是良好的做法(并且有意义)

其他资源

Detect closed network connection

**** Detection of Half-Open (Dropped) Connections **** Stephen Cleary

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读