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.*; public abstract class SocketAddress {   public SocketAddress( ) {} } 

At least theoretically, this class can be used for both TCP and 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( ) public SocketAddress getLocalSocketAddress( ) 

Both of these methods return null if the socket is not yet connected.

A SocketAddress is necessary to connect an unconnected socket via the connect( ) method:

 public void connect(SocketAddress endpoint) throws IOException 

For 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( ); socket.connect(yahoo); 

Not all socket implementations can use the same subclasses of 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 IOException 

The default, 0, means wait forever.



Java Network Programming
Java Network Programming, Third Edition
ISBN: 0596007213
EAN: 2147483647
Year: 2003
Pages: 164

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net