我正在使用通过 Tcpstream
实例化的 StreamWriter
像这样
streamWriter = new StreamWriter(tcpClient.GetStream());
我对关于异常的后续调用的行为感到困惑。以下两个函数预计会引发 IOException
令人惊讶的是,当 tcpClient
连接到的服务器断开连接时,它们不会引发 IOException
,因此底层 TCP 客户端连接已断开。这两行执行时不会引发任何异常。为什么 ?
streamWriter.WriteLine(strBuffer);
streamWriter.Flush();
编辑:这篇文章也帮助我理解了原因,除了这里的专家回复。 http://social.msdn.microsoft.com/Forums/sk/netfxnetcom/thread/b177a935-7430-4812-9555-f747748df1af 本质上,NetworkStream.Write 在调用 StreamWriter 的 WriteLine 时被调用,这将写入传出缓冲区并返回,不会阻塞,除非缓冲区已满。操作系统维护的内部缓冲区包含未发送的数据,操作系统将继续尝试发送这些数据,直到给定次数的尝试失败。 WriteLine 会抛出 IOException 但不一定每次都抛出..
最佳答案
这个问题与StreamWriter
无关,它只是关于NetworkStream
的行为。
NetworkStream.Flush()
是空操作。特别是在接收方确认刷新之前发送的所有字节之前不会阻塞。
The Flush method implements the Stream.Flush method; however, because NetworkStream is not buffered, it has no affect on network streams. Calling the Flush method does not throw an exception.
(来自 NetworkStream.Flush Method (MSDN))
你会在某个时候得到你的异常(exception),但那可能要晚得多。本质上,NetworkStream
和操作系统都不知道 TCP 连接已经断开,因此它们不会引发异常。
关于c# - StreamWriter 是否抛出异常底层连接断开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13858433/