I am using StreamWriter instantiated over a Tcpstream
like this
streamWriter = new StreamWriter(tcpClient.GetStream());
I am confused about the behavior of following calls with regards to Exceptions. The following two functions are expected to raise IOException Surprisingly they do not raise the IOException when the server to which the tcpClient is connected is disconnected and therefore the underlying TCP client connection is broken.. These two lines execute without raising any Exception. Why ?
streamWriter.WriteLine(strBuffer);
streamWriter.Flush();
EDIT: This particular post also helped me understand the reason, besides the replies here from the experts.
http://social.msdn.microsoft.com/Forums/sk/netfxnetcom/thread/b177a935-7430-4812-9555-f747748df1af
In essence the NetworkStream.Write is called when WriteLine of StreamWriter is called, This writes to the out-going buffer and returns, without blocking, unless if the buffer was full. The internal buffer maintained by OS contains unsent data, which OS will keep trying to send until a given number of attempts fail.
WriteLine will throw IOException but not necessarily every time..
This issue is unrelated to
StreamWriter, it’s only about the behavior ofNetworkStream.NetworkStream.Flush()is a no-op. In particular is does not block until the recipient has acknowledged all bytes sent prior to the flush.(from NetworkStream.Flush Method (MSDN))
You will get your exception at some point, but that can be much later. Essentially neither
NetworkStreamnor the OS know that the TCP connection is already broken, so they won’t raise an exception.