From what I understand, linger is a setting allowing to keep the connection some delay after close for the final data to have time to be read.
I have this example:
@Ignore
public class SocketTTest
{
@Test
public void socketTest() throws Throwable
{
new Thread(() -> {
try
{
ServerSocket serverSocket = new ServerSocket(5555);
while(true)
{
//keep listening
Socket socket = serverSocket.accept();
socket.setSoLinger(false, 0);
InputStream in = socket.getInputStream();
System.out.println(in.read());
Thread.sleep(2000);
System.out.println(in.read());
in.close();
socket.close();
System.exit(0);
}
}
catch(Throwable ex)
{
ex.printStackTrace();
}
}).start();
Socket socket = new Socket("localhost", 5555);
socket.setSoLinger(false, 0);
OutputStream out = socket.getOutputStream();
out.write(1);
out.write(2);
out.close();
socket.close();
synchronized(this)
{
wait();
}
}
}
And the output
1
2
How does the 2 is read? The linger is disabled, the socket shouldn't be in a unreadable state when coming out of sleep?
Shouldn't
setSoLinger()
tofalse
cut this connection?
No.
From what I understand, linger is a setting allowing to keep the connection some delay after close for the final data to have time to be read.
No. TCP already does that by default. It is a setting that causes close()
to block for a specified timeout while there is still pending data waiting to be sent. There is little point in setting it, and all that your code has accomplished by calling setSoLinger(false, 0)
is to reassert the default setting. Your code will work equally well without it, and with or without the sleeps.
SO_LINGER can also be used to abuse TCP/IP by resetting the connection, but you aren't doing that here.
How the 2 is read?
Because TCP doesn't lose data in this way.
The linger is disabled
True, but it already was, see above.
the socket shouldn't be in an unreadable state when it comes out of sleep?
I don't know what this means. Either you're contradicting yourself or there is an inadvertent double negative here.