为什么在写入关闭的连接(第一次)时 TcpClient.Write 不会抛出异常?

发布于 2024-08-02 06:18:15 字数 360 浏览 3 评论 0原文

我有一个简单的程序,它使用 TcpClient 和 SslStream 将数据写入套接字。

为了测试它,我整夜运行该程序,这样我的程序就会打开连接,很长一段时间不写入任何内容,因此防火墙或远程服务器会关闭连接。今天早上,我查看了 TCPView 并验证连接已关闭,然后告诉我的程序写入套接字。

Write 上没有抛出异常。但是,下一个 Write 确实按预期抛出了此异常:“System.IO.IOException:无法将数据写入传输连接:现有连接被远程主机强制关闭”

我可以明白为什么 TcpClient.Connected 甚至可以返回 True如果确实没有连接,但为什么 Write 不会在实际关闭的连接上抛出异常(如 TCPView 中验证的)?

I have a simple program that uses TcpClient and SslStream to write data to a socket.

To test it I ran the program over night so my program would open the connection, write nothing for a long time, so the firewall or remote server would close the connection. This morning I took a look at TCPView and verified the connection was closed and then told my program to Write to the socket.

No exception was thrown on Write. However, the next Write did thrown this exception as expected: “System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host”

I can see why TcpClient.Connected could return True even if it really wasn’t connected, but why would Write not throw an exception on a connection that was actually closed (as verified in TCPView)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少跟Wǒ拽 2024-08-09 06:18:15

这是因为 TCP/IP 协议的工作方式。
当您调用 TcpClient.Write 时,数据正在发送到服务器,并且该函数返回成功,而无需等待服务器响应。

与此同时,服务器返回一个错误。
你这边的 Tcp/IP 堆栈注意到这一点,下次你尝试编写它时会抛出异常

That's because of the way TCP/IP protocol works.
When you call TcpClient.Write data is being sent to the server, and the function returns success without waiting for a server response.

In the meantime the server returns an error.
Tcp/IP stack on your side notices that and next time you try to write it will throw an exception

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文