Java Socket setSoLinger() method

The setSoLinger() method of Java Socket class enables or disables the SO_LINGER option with the given linger time in seconds. It is used to specify how the close() method affects socket using a connection-oriented protocol. The timeout value is platform-specific, and this setting only affects the socket close.

Syntax

Parameter

on - whether the 'linger' should be enabled or not.M

linger - how long to linger for, if the parameter 'on' is true.

Return

NA

Throws

SocketException - if an error is there in the underlying protocol, such as a TCP error.

IllegalArgumentException - if the linger value is less than 0.

Example 1

Test it Now

Output:

Timeout value: 90

Example 2

Test it Now

Output:

Timeout value: -1

Example 3

Test it Now

Output:

Exception in thread "main" java.lang.IllegalArgumentException: invalid value for SO_LINGER
	at java.net.Socket.setSoLinger(Socket.java:1021)
	at com.javaTpoint.JavaSocketSetSoLingerExample3.main(JavaSocketSetSoLingerExample3.java:14)

Example 4

Test it Now

Output:

Exception in thread "main" java.net.SocketException: Socket is closed
	at java.net.Socket.setSoLinger(Socket.java:1016)
	at com.javaTpoint.JavaSocketSetSoLingerExample4.main(JavaSocketSetSoLingerExample4.java:18)




Latest Courses