Blocking TCP socket write then immediatelly close - is it a problem?
.net, communication, sockets, tcp
Solution
It's is absolutelly OK to call Close just after Socket.Write. Here's what TCP RFC 793 says:
"Closing connections is intended to be a graceful operation in the sense that outstanding SENDs will be transmitted (and retransmitted), as flow control permits, until all have been serviced. Thus, it should be acceptable to make several SEND calls, followed by a CLOSE, and expect all the data to be sent to the destination."
The confusion, in part, comes from MSDN documentation:
"If you are using a connection-oriented protocol, Send will block until all of the bytes in the buffer are sent"
In reality, blocking Write only copies data to outgoing buffer and returns. It's the network provider responsibility, under RFC 793, to complete the delivery of the data after Socket.Close is called (as long as the connection is not dead, of course).
Problem
I have a sender that TCP-connects, sends block of data, and closes the socket. I'd like to write the simplest, but reliable program that does the above. The first thing comes into mind (e.g. in .NET, although the question relevant to sockets in general): ``` // assuming LingerOption(false), NoDelay set to whatever var client = new TcpClient().Connect(server, port); var stream = client.GetStream(); stream.Write(data, 0, data.Length); stream.Close(); client.Close(); ``` Now to some questions basing on reading of various MSDN and other materials: - stream.Close() calls Socket.Close(). Socket.Close() is said to close immediatelly, discarding network buffer data which was not send. This is bad. But, Socket.Write documentation says that if the socket is blocking (it is, by default), Socket.Write will block until all the data is sent. So there's no problem, right? - In general, can there be a situation, in which the code above will result in receiver not receiving everything what was sent in Write? (assuming 100% reliable network)