Why does TcpClient.Write not throw an exception when writing to a closed connection (for the first time)?

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

To test it, I ran the program overnight, so that my program opened the connection, didn’t write anything for a long time, so the firewall or the remote server will close the connection. This morning I looked at TCPView and confirmed that the connection was closed, and then informed my program about writing to the socket.

No exception was thrown on the record. However, the following Write made this exception as expected: "System.IO.IOException: Failed to write data to transport connection: existing connection was forcibly closed by the remote host"

I see why TcpClient.Connected can return True even if it is not really connected, but why Write does not throw an exception in the connection that was actually closed (as checked in TCPView)?

+3
source share
1 answer

This is due to how the TCP / IP protocol works. When you call TcpClient.Write, data is sent to the server, and the function returns success without waiting for the server to respond.

Meanwhile, the server returns an error. The Tcp / IP stack on your side notices that the next time you try to write it, you will get an exception

+5
source

Source: https://habr.com/ru/post/1715549/


All Articles