When does java.net.Socket.setSoTimeout(...) throws SocketException?
The documentation says that Socket
's setSoTimeout(int)
method
throws SocketException - if there is an error in the underlying protocol, such as a TCP error
Have you ever caught this exception? When using TCP sockets, what kind of TCP error could make this method throw the exception?
EDIT:
Let me try to be a bit more specific and deeper. I'm not looking for the trivial (eg, a closed socket will throw this exception) that can be easily found elsewhere.
Suppose the Socket
(representing a TCP connection) has just been created, is connected, and not yet closed. I've not yet performed any reads/writes on it. I'm running on Linux (Ubuntu Server 11.04), so we can forget the case in which the TCP implementation doesn't support read timeouts.
Now, can this exception be thrown in this situation? If so, what does it mean? Is 开发者_JAVA百科it something specific to the current Socket
instance? If I simply close()
it and somehow obtain a new one, should it work? Is it a bigger problem I cannot recover from (such as a problem in the operating system), and should better shutdown my application?
The SocketException
, in this scenario, is either thrown if the socket is closed or closing.
It can also be thrown to indicate an error that was generated by the native TCP stack implementation. If, for instance, you are on Windows, setSoTimeout
will likely boil down to an invocation of the setsockopt
function in the Windows Winsock API. An error from this method would indicate some deeper issue in the winsock subsystem (unable to initialize) or it could also be thrown if you attempt to set socket options when a blocking operation is in progress on the socket (by another thread, for instance). For this reason, you should strive to only modify socket options at creation time, avoiding to change any options once you've connected the socket and started doing I/O on it.
You can read more here if you are curious.
java.net.SocketException
is thrown when you call setSoTimeout
on a closed socket.
As always, use the forc..source.
精彩评论