What does the Socket method setSoLinger() do and when should I use it?
Created May 4, 2012
The SO_LINGER option is used to specify how the close() method affects socket using a connection-oriented protocol (i.e. TCP/IP, not UDP). A good reference for this option is UNIX Network Programming, 2nd Edition, by W. Richard Stevens, pp.187-191.
On invoking the close() method, there are several things that can happen, depending on the state of SO_LINGER:
The default scenario doesn't guarantee that the data is delivered if, for example, you have a machine crash; as far as you know the return from the close() implies that data has been sent at the application level. However, if the remote machine crashes then the data in the send buffer may be lost. The third scenario above provides this mechanism by returning from the close() only when the data has been sent by the system, so you can guarantee that data has been delivered (unless an exception occurs). However, this can be achieved equally as well by performing an application acknowledge without the use of this low-level technique and I would recommend that.
The second scenario would be used in the event that you wish to terminate the connection to the client immediately without sending data.