Java Reference
In-Depth Information
}
}
You can improve this slightly by using the noargs ServerSocket() constructor, which
does not throw any exceptions and does not bind to a port. Instead, you call the bind()
method to bind to a socket address after the ServerSocket() object has been construcā€
ted:
ServerSocket server = new ServerSocket ();
try {
SocketAddress address = new InetSocketAddress ( port );
server . bind ( address );
// ... work with the server socket
} finally {
try {
server . close ();
} catch ( IOException ex ) {
// ignore
}
}
In Java 7, ServerSocket implements AutoCloseable so you can take advantage of try-
with-resources instead:
try ( ServerSocket server = new ServerSocket ( port )) {
// ... work with the server socket
}
After a server socket has been closed, it cannot be reconnected, even to the same port.
The isClosed() method returns true if the ServerSocket has been closed, false if it
hasn't:
public boolean isClosed ()
ServerSocket objects that were created with the noargs ServerSocket() constructor
and not yet bound to a port are not considered to be closed. Invoking isClosed() on
these objects returns false. The isBound() method tells you whether the ServerSock
et has been bound to a port:
public boolean isBound ()
As with the isBound() method of the Socket class discussed in the Chapter 8 , the name
is a little misleading. isBound() returns true if the ServerSocket has ever been bound
to a port, even if it's currently closed. If you need to test whether a ServerSocket is open,
you must check both that isBound() returns true and that isClosed() returns false.
For example:
public static boolean isOpen ( ServerSocket ss ) {
return ss . isBound () && ! ss . isClosed ();
}
Search WWH ::




Custom Search