下面是我的NetworkStream的代码,没有任何处理:
using (NetworkStream stream = client.GetStream()) { stream.ReadTimeout = ReadTimeout; ... if (stream.CanRead && stream.DataAvailable) bytesRead = stream.Read(receivedBytes, 0, BufferSize); ... stream.Write(ack, 0, 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 offset, 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