Java Reference
In-Depth Information
} else {
// do something else...
}
However, this is not a perfect test. If the socket has never been connected in the first
place, isClosed() returns false, even though the socket isn't exactly open.
The Socket class also has an isConnected() method. The name is a little misleading.
It does not tell you if the socket is currently connected to a remote host (like if it is
unclosed). Instead, it tells you whether the socket has ever been connected to a remote
host. If the socket was able to connect to the remote host at all, this method returns true,
even after that socket has been closed. To tell if a socket is currently open, you need to
check that isConnected() returns true and isClosed() returns false. For example:
boolean connected = socket . isConnected () && ! socket . isClosed ();
Finally, the isBound() method tells you whether the socket successfully bound to the
outgoing port on the local system. Whereas isConnected() refers to the remote end of
the socket, isBound() refers to the local end. This isn't very important yet. Binding will
become more important when we discuss server sockets in Chapter 9 .
toString()
The Socket class overrides only one of the standard methods from java.lang.Ob
ject : toString() . The toString() method produces a string that looks like this:
Socket[addr=www.oreilly.com/198.112.208.11,port=80,localport=50055]
This is useful primarily for debugging. Don't rely on this format; it may change in the
future. All parts of this string are accessible directly through other methods (specifically
getInetAddress() , getPort() , and getLocalPort() ).
Because sockets are transitory objects that typically last only as long as
the connection they represent, there's not much reason to store them
in hash tables or compare them to each other. Therefore, Socket does
not override equals() or hashCode() , and the semantics for these
methods are those of the Object class. Two Socket objects are equal
to each other if and only if they are the same object.
Setting Socket Options
Socket options specify how the native sockets on which the Java Socket class relies send
and receive data. Java supports nine options for client-side sockets:
• TCP_NODELAY
Search WWH ::




Custom Search