Java Reference
In-Depth Information
SO_LINGER
public
void
setSoLinger
(
boolean
on
,
int
seconds
)
throws
SocketException
public
int
getSoLinger
()
throws
SocketException
The SO_LINGER option specifies what to do with datagrams that have not yet been
sent when a socket is closed. By default, the
close()
method returns immediately; but
the system still tries to send any remaining data. If the linger time is set to zero, any
unsent packets are thrown away when the socket is closed. If SO_LINGER is turned on
and the linger time is any positive value, the
close()
method blocks while waiting the
specified number of seconds for the data to be sent and the acknowledgments to be
received. When that number of seconds has passed, the socket is closed and any re‐
maining data is not sent, acknowledgment or no.
These two methods each throw a
SocketException
if the underlying socket imple‐
mentation does not support the SO_LINGER option. The
setSoLinger()
method can
also throw an
IllegalArgumentException
if you try to set the linger time to a negative
value. However, the
getSoLinger()
method may return -1 to indicate that this option
is disabled, and as much time as is needed is taken to deliver the remaining data; for
example, to set the linger timeout for the
Socket s
to four minutes, if it's not already
set to some other value:
if
(
s
.
getTcpSoLinger
()
==
-
1
)
s
.
setSoLinger
(
true
,
240
);
The maximum linger time is 65,535 seconds, and may be smaller on some platforms.
Times larger than that will be reduced to the maximum linger time. Frankly, 65,535
seconds (more than 18 hours) is much longer than you actually want to wait. Generally,
the platform default value is more appropriate.
SO_TIMEOUT
public
void
setSoTimeout
(
int
milliseconds
)
throws
SocketException
public
int
getSoTimeout
()
throws
SocketException
Normally when you try to read data from a socket, the
read()
call blocks as long as
necessary to get enough bytes. By setting SO_TIMEOUT, you ensure that the call will
not block for more than a fixed number of milliseconds. When the timeout expires, an
InterruptedIOException
is thrown, and you should be prepared to catch it. However,
the socket is still connected. Although this
read()
call failed, you can try to read from
the socket again. The next call may succeed.
Timeouts are given in milliseconds. Zero is interpreted as an infinite timeout; it is the
default value. For example, to set the timeout value of the
Socket
object
s
to 3 minutes
if it isn't already set, specify 180,000 milliseconds:
if
(
s
.
getSoTimeout
()
==
0
)
s
.
setSoTimeout
(
180000
);