9.5 Socket Addresses
The SocketAddress class introduced in Java 1.4 represents a
connection endpoint. The actual
java.net.SocketAddress class is an empty abstract
class with no methods aside from a default constructor:
package java.net.*;At least theoretically, this class can be used for both TCP and
public abstract class SocketAddress {
public SocketAddress( ) {}
}
non-TCP sockets. Subclasses of SocketAddress
provide more detailed information appropriate for the type of socket.
In practice, only TCP/IP sockets are currently supported.The primary purpose of the SocketAddress class is
to provide a convenient store for transient socket connection
information such as the IP address and port that can be reused to
create new sockets, even after the original socket is disconnected
and garbage collected. To this end, the Socket
class offers two methods that return SocketAddress
objects: getRemoteSocketAddress( )
returns the address of the system being connected to and
getLocalSocketAdddress( ) returns the address from
which the connection is made:
public SocketAddress getRemoteSocketAddress( )Both of these methods return null if the socket is not yet connected.A SocketAddress is necessary to connect an
public SocketAddress getLocalSocketAddress( )
unconnected socket via the connect( ) method:
public void connect(SocketAddress endpoint) throws IOExceptionFor example, first you might connect to Yahoo, then store its address:
Socket socket = new Socket("www.yahoo.com", 80);
SocketAddress yahoo = socket.getRemoteSocketAddress( );
socket.close( );Later, you could reconnect to Yahoo using this address:socket = new Socket( );Not all socket implementations can use the same subclasses of
socket.connect(yahoo);
SocketAddress. If an instance of the wrong type is
passed to connect( ), it throws an
IllegalArgumentException.You can pass an int as the second argument to
specify the number of milliseconds to wait before the connection
times out:
public void connect(SocketAddress endpoint, int timeout) throws IOExceptionThe default, 0, means wait forever.
• Table of Contents• Index• Reviews• Reader Reviews• Errata• AcademicJava Network Programming, 3rd EditionBy
Elliotte Rusty Harold Publisher: O'ReillyPub Date: October 2004ISBN: 0-596-00721-3Pages: 706
Thoroughly revised to cover all the 100+ significant updates
to Java Developers Kit (JDK) 1.5, Java Network
Programming is a complete introduction to
developing network programs (both applets and applications)
using Java, covering everything from networking fundamentals
to remote method invocation (RMI). It includes chapters on
TCP and UDP sockets, multicasting protocol and content
handlers, servlets, and the new I/O API. This is the
essential resource for any serious Java developer.