by Debasis Samanta
The java.net package contains classes and interfaces, and related exception that provides a URL and a URL connection, TCP, UDP, IP, and support socket connections. It also includes classes that represents an Internetaddress, and binary-to- text converter. Following is the diffetent constituent in this package :
Classes Class ContentHandler Class DatagramPacket Class DatagramSocket Class InetAddress Class ServerSocket Class Socket Class SocketImpl Class URL Class URLConnection Class URLEncoder Class URLStreamHandler Interfaces Interface ContentHandlerFactory Interface SocketImplFactory Interface URLStreamHandlerFactory Exceptions Class MalformedURLException Class ProtocolException Class SocketException Class UnknownHostException Class UnknownServiceException
The abstract class ContentHandler is the superclass of all classes that read an Object from a URL Connection. An application does not generally call the getContentHandler method in this class directly. Instead, an application calls the getContent method in class URL or in URLConnection. The application's content handler factory (an instance of a class that implements the interface ContentHandlerFactory set up by a call to setContentHandler and is called with a String giving the MIME type of the object being received on the socket. The factory returns an instance of a subclass of ContentHandler, and its getContent method is called to create the object.
This class has the following structure : public abstract class java.net.ContentHandler extends java.lang.Object { // Constructors public ContentHandler(); // The default constructor for class ContentHandler. // Methods public abstract Object getContent(URLConnection urlc); /* Given an URL connect stream positioned at the beginning of the representation of an object, this method reads that stream and creates an object from it. Returns : The object read by the ContentHandler. Throws : IOException, if an IO error occurs while reading the object. */ }
This class represents a datagram packet. Datagram packets are used to implement a connectionless packet delivery service. Each message is routed from one machine to another based solely on information contained within that packet. Multiple packets sent from a machine to another might be routed differently, and might arrive in any order.
The structure of this class is shown below : public final class java.net.DatagramPacket extends java.lang.Object { // Constructors public DatagramPacket(byte ibuf[], int ilength); /* Constructs a DatagramPacket for receiving packets of length ilength. The length argument must be less than or equal to ibuf.length. */ public DatagramPacket(byte ibuf[], int ilength, InetAddress iaddr,int iport); /* Constructs a DatagramPacket for sending packets of length ilength to the specified port number on the specified host. The length argument must be less than or equal to ibuf.length. */ // Methods public InetAddress getAddress(); public byte[] getData(); public int getLength(); public int getPort(); } The operation performed by the various methods are listed in Table 8.1.
Table 8.1
Method |
Description |
getAddress() |
Returns : the IP address of the machine to which this datagram is being sent, or from which the datagram was received. |
getData() |
Returns : the data received, or the data to be sent. |
getLength() |
Returns : the length of the data to be sent, or the length of the data received. |
getPort() |
Returns : the port number on the remote host to which this datagram is being sent, or from which the dagram was received |
This class represents a socket for sending and receiving datagram packets. A datagram socket is the sending or receiving point for a connectionless packet delivery service. Each packet sent or received on a datagram socket is individually addressed and routed. Multiple packets sent from a machine to another may be routed differently, and may arrive in any order.
public class java.net.DatagramSocket extends java.lang.Object { // Constructors public DatagramSocket(); /* Constructs a datagram socket and binds it to any available port on the local host machine. Throws : SocketException, if the socket could not be opened, or the socket could not bind the specified local port. */ public DatagramSocket(int port); /* Constructs a datagram socket and binds it to the specified port on the local host machine. Throws : SocketException, if the socket could not be opened, or the socket could not bind the specified local port. */ // Methods public void close(); protected void finalize(); public int getLocalPort(); public void receive(DatagramPacket p); public void send(DatagramPacket p); } Methods are described in Table 8.2.
Table 8.2
Method |
Description |
close() |
Closes this datagram socket. |
finalize() |
Ensures that this socket is closed if there are no longer any references to this socket. |
getLocalPort() |
Returns : the port number on the local host to which this socket is bound.
|
receive(DatagramPacket p) |
Receives a datagram packet from this socket. When this method returns, the DatagramPacket's buffer is filled with the data received. The datagram packet also contains the sender's IP address, and the port number on the sender's machine. This method blocks until a datagram is received. The length field of the datagram packet object contains the length of the received message. If the message is longer than the buffer length, the message is truncated. Throws : IOException, if an I/O error occurs. |
send(DatagramPacket p) |
Sends a datagram packet from this socket. The DatagramPacket includes information indicating the data to be sent, its length, the IP address of the remote host, and the port number on the remote host. Throws : IOException, if an I/O error occurs. |
This class represents an Internet Protocol (IP) address. Applications should use the methods getLocalHost, getByName , or getAllByName to create a new InetAddress instance. The class structure is shown as below :
public final class java.net.InetAddress extends java.lang.Object { // Methods public boolean equals(Object obj); public byte[] getAddress(); public static InetAddress[] getAllByName(String host); public static InetAddress getByName(String host); public String getHostName(); public static InetAddress getLocalHost(); public int hashCode(); public String toString(); } Methods are described in Table 8.3.
Table 8.3
Method |
Description |
equals(Object obj) |
The result is true if and only if the argument is not null and it represents the same IP address as this object. |
getAddress() |
Determines the raw IP address of this InetAddress object. The result is in network byte order : the highest order byte of the address is in getAddress(). |
getAllByName(String host) |
Returns : an array of all the IP addresses for a given host name. Throws : UnknownHostException, if no IP address for the host could be found. |
getByName(String host) |
Determines the IP address of a host, given the host's name. The host name can either be a machine name, such as "java.sun.com" or a string representing its IP address, such as "198.87.26.123". |
getHostName() |
Throws
: UnknownHostException,
if no IP address for the host could be found. |
getLocalHost() |
Returns : the IP address of the local host. Throws : UnknownHostException , if no IP address for the host could be found. |
hashCode() |
Returns : a hash code value for this IP address. |
toString() |
Returns : a string representation of this IP address. |
This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.
The actual work of the server socket is performed by an instance of the SocketImpl class. An application can change the socket factory that creates the socket implementation to configure itself to create sockets appropriate to the local firewall
Methods are described in Table 8.4public final class java.net.ServerSocket extends java.lang.Object { // Constructors public ServerSocket(int port); /* Creates a server socket on a specified port. A port of 0 creates a socket on any free port. The maximum queue length for incoming connection indications (a request to connect) is set to 50. If a connection indication arrives when the queue is full, the connection is refused. If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created. Throws : IOException, if an IO error occurs when opening the socket. */ public ServerSocket(int port, int count); /* Creates a server socket and binds it to the specified local port number. A port number of 0 creates a socket on any free port. The maximum queue length for incoming connection indications (a request to connect) is set to the count parameter. If a connection indication arrives when the queue is full, the connection is refused. If the application has specified a server socket factory , that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created. Throws : IOException, if an IO error occurs when opening the socket. */ // Methods public Socket accept(); public void close(); public InetAddress getInetAddress(); public int getLocalPort(); public static void setSocketFactory(SocketImplFactory fac); public String toString(); }
Table 8.4
Method |
Description |
accept() |
Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made. Throws : IOException, If an I/O error occurs when waiting for a connection. |
close() |
Closes this socket. Throws : IOException, If an I/O occurs error when closing the socket. |
getInetAddress() |
Returns : The address to which this socket is connected, or null if the socket is not yet connected. |
getLocalPort() |
Returns : the port number to which this socket is listening. |
setSocketFactory(SocketImplFactory fac) |
Sets the server socket implementation factory for the application. The factory can be specified only once. When an application creates a new server socket, the socket implementation factory's createSocketImpl method is called to create the actual socket implementation. Throws : SocketException, if the factory has already been defined, and Throws : IOException, If an I/O error occurs when setting the socket factory. |
toString() |
Returns : a string representation of this socket. |
This class implements client sockets (also called just "sockets"). A socket is a end point for communication between two machines.
The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall.
public final class java.net.Socket extends java.lang.Object { // Constructors public Socket(InetAddress address, int port); /* Creates a stream socket and connects it to the specified port number at the specified IP address. If the application has specified a socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created. Throws : IOException, if an I/O error occurs when creating the socket. */ public Socket(InetAddress address, int port, boolean stream); /* Creates a socket and connects it to the specified port number at the specified IP address. If the stream argument is true, this creates a stream socket. If the stream argument is false, it creates a datagram socket. Throws : IOException, If an I/O error occurs when creating the socket. */ public Socket(String host, int port); /* Creates a stream socket and connects it to the specified port number on the named host. Throws : IOException, If an I/O error occurs when creating the socket. */ public Socket(String host, int port, boolean stream); /* Creates a stream socket and connects it to the specified port number on the named host.If the stream argument is true, this creates a stream socket. If the stream argument is false, it creates a datagram socket. Throws : IOException, If an I/O error occurs when creating the socket. */ // Methods public void close(); public InetAddress getInetAddress(); public InputStream getInputStream(); public int getLocalPort(); public OutputStream getOutputStream(); public int getPort(); public static void setSocketImplFactory(SocketImplFactory fac); public String toString(); } Methods are described in Table 8.5
Table 8.5
The abstract class SocketImpl is a common superclass of all classes that actually implement sockets. It is used to create both client and server sockets. A "plain" socket implements these methods exactly as described, without attempting to go through a firewall or proxy.
public abstract class java.net.SocketImpl extends java.lang.Object { // Member elements protected InetAddress address; // The IP address of the remote end of this socket. protected FileDescriptor fd; // The file descriptor object for this socket. protected int localport; // The local port number to which this socket is connected. protected int port; // The port number on the remote host to which this socket is connected. // Constructors public SocketImpl(); // The default constructor for a socket implementation. // Methods protected abstract void accept(SocketImpl s); protected abstract int available(); protected abstract void bind(InetAddress host, int port); protected abstract void close(); protected abstract void connect(InetAddress address, int port); protected abstract void connect(String host, int port); protected abstract void create(boolean stream); protected FileDescriptor getFileDescriptor(); protected InetAddress getInetAddress(); protected abstract InputStream getInputStream(); protected int getLocalPort(); protected abstract OutputStream getOutputStream(); protected int getPort(); protected abstract void listen(int count); public String toString(); } Methods are described in Table 8.6.
Table 8.6
Method |
Description |
accept(SocketImpl s) |
Accepts a connection. Throws : IOException, if an I/O error occurs when accepting the connection. |
available() |
Returns:
the
number of bytes that can be read from this socket without
blocking. |
bind(InetAddress host, int port) |
Binds this socket to the specified port number on the specified host. Throws : IOException , if an I/O error occurs when binding this socket. |
close() |
Closes this socket. Throws : IOException, if an I/O error occurs when closing this socket |
connect(InetAddress address, int port) |
Connects this socket to the specified port number on the specified host. Throws : IOException, if an I/O error occurs when attempting a connection. |
connect(String host, int port) |
Connects this socket to the specified port on the named host. Throws : IOException, if an I/O error occurs when connecting to the remote host. |
create(boolean stream) |
Creates a socket. Throws : IOException, if an IO error occurs while creating the socket. |
getFileDescriptor() |
Returns : the value of this socket's fd field. |
getInetAddress() |
Returns : the value of this socket's address field. |
getInputStream() |
Returns : a stream for reading from this socket. Throws : IOException, f an I/O error occurs when creating the input stream. |
getLocalPort() |
Returns : the value of this socket's localport field. |
getOutputStream() |
Returns : an output stream for writing to this socket. Throws : IOException, If an I/O error occurs when creating the output stream |
getPort() |
Returns : the value of this socket's port field.
|
listen(int count) |
Sets the maximum queue length for incoming requests to this socket to the count argument. If a connection request arrives when the queue is full, the connection is refused. Throws : IOException, if an I/O error occurs when creating the queue. |
toString() |
Returns : a string representation of this socket. |
Class URL represents a Uniform Resource Locator-a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine.
The class structure is shown below :
public final class java.net.URL extends java.lang.Object { // Constructors public URL(String spec); /* Creates a URL object from the String representation. This constructor is equivalent to a call to the two-argument constructor with a null first argument. Throws : MalformedURLException, if the string specifies an unknown protocol. */ public URL(String protocol, String host, int port, String file); /* Creates a URL object from the specified protocol, host, port number, and file. Throws : MalformedURLException, if the string specifies an unknown protocol. */ public URL(String protocol, String host, String file); /* Creates an absolute URL from the specified protocol name, host name, and file name. The default port for the specified protocol is used. Throws : MalformedURLException, if the string specifies an unknown protocol. */ public URL(URL context, String spec); /* Creates a URL by parsing the String specification within a specified context: If the context argument is not null and the spec argument is a partial URL specification, then any of the strings missing components are inherited from the context argument. Throws : MalformedURLException, if no protocol is specified, or an unknown protocol is found. */ // Methods public boolean equals(Object obj); public final Object getContent(); public String getFile(); public String getHost(); public int getPort(); public String getProtocol(); public String getRef(); public int hashCode(); public URLConnection openConnection(); public final InputStream openStream(); public boolean sameFile(URL other); public static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac); public String toExternalForm(); public String toString(); } Methods are stated in Table 8.7.
Table 8.7
The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL. In general, creating a connection to a URL is a multi-step process.
First, the connection object is created by invoking openConnection on a URL, then setup parameters are manipulated, then the actual connection to the remote object is made, and finally the remote object is available. There are a set of properties that apply before the connection is made, and a set that apply after:
Most of these properties have a set and a get method. The first three in the "before" column also have corresponding "Default" properties that specify the default values used in subsequent requests where the property is not specified.
In the common case, all of these properties can be ignored: the pre-connection properties default to sensible values, and the post-connection properties are often uninteresting. For most clients of this interface, there are only two interesting methods: getInputStream and getObject, which are mirrored in the URL class by convenience methods.
This very useful class is having the following constituents : public abstract class java.net.URLConnection extends java.lang.Object { // Member elements protected boolean allowUserInteraction; /* This value of this field can be set by the setAllowUserInteraction method. Its value can be accessed by the getAllowUserInteraction method . Its default value is the value of the argument method to the last call to the setDefaultAllowUserInteraction method. If true, this URL is being examined in a context which it makes sense to allow user interactions such as popping up an authentication dialog. If false, then no user interaction is allowed. */ protected boolean connected; /* If false, this connection object has not created a communications link to the specified URL. If true, the communications link has been established. */ protected boolean doInput; /* This variable is set by the setDoInput method. Its value can be accessed by the getDoInput method . A URL connection can be used for input and/or output. Setting the doInput flag to true indicates that the application intends to read data from the URL connection. The default value of this field is true. */ protected boolean doOutput; /* This variable is set by the setDoOutput method. Its value can be accessed by the getDoInput method. A URL connection can be used for input and/or output. Setting the do-Output flag to true indicates that the application intends to write data to the URL connection. The default value of this field is false. */ protected long ifModifiedSince; /* Some protocols support skipping the fetching of the object unless the object has been modified more recently than a certain time. A non-zero value is interpreted as the time corresponding to if-Modified-Since seconds since January 1, 1970, GMT. The object is fetched only if it has been modified more recently than that time. This variable is set by the setIfModifiedSince method . Its value can be accessed by the getIfModifiedSince method. The default value of this field is 0, indicating that the fetching must always occur. */ protected URL url; /* The URL representing the remote object on the World Wide Web to which this connection is opened. The value of this field can be accessed by the getURL method. The default value of this variable is the value of the URL argument in the URLConnection constructor. */ protected boolean useCaches; /* This field is set by the setUseCaches method. Its value can be accessed by the getUseCaches method . Its default value is the value of the last argument to the method setDefaultUseCaches. If true, the protocol is allowed to use caching whenever it can. If false, the protocol must always try to get a fresh copy of the object. */ // Constructors protected URLConnection(URL url); /* Constructs a URL connection to the specified URL. A connection to the object referenced by the URL is not created. */ // Methods public abstract void connect(); public boolean getAllowUserInteraction(); public Object getContent(); public String getContentEncoding(); public int getContentLength(); public String getContentType(); public long getDate(); public static boolean getDefaultAllowUserInteraction(); public static String getDefaultRequestProperty(String key); public boolean getDefaultUseCaches(); public boolean getDoInput(); public boolean getDoOutput(); public long getExpiration(); public String getHeaderField(int n); public String getHeaderField(String name); public long getHeaderFieldDate(String name, long Default); public int getHeaderFieldInt(String name, int Default); public String getHeaderFieldKey(int n); public long getIfModifiedSince(); public InputStream getInputStream(); public long getLastModified(); public OutputStream getOutputStream(); public String getRequestProperty(String key); public URL getURL(); public boolean getUseCaches(); protected static String guessContentTypeFromName(String fname); protected static String guessContentTypeFromStream(InputStream is); public void setAllowUserInteraction(boolean allow); public static void setContentHandlerFactory(ContentHandlerFactory fac); public static void setDefaultAllowUserInteraction(boolean default); public static void setDefaultRequestProperty(String key, String value); public void setDefaultUseCaches(boolean uCaches); public void setDoInput(boolean doinput); public void setDoOutput(boolean dooutput); public void setIfModifiedSince(long modify); public void setRequestProperty(String key, String value); public void setUseCaches(boolean uCaches); public String toString(); } Methods are stated in Table 8.8.
Table 8.8
The class contains a utility method for converting a String into a MIME format called "x- www-form-urlencoded" format. To convert a String, each character is examined in turn :
public class java.net.URLEncoder extends java.lang.Object { // Methods public static String encode(String s); // Translates a String into x-www-form-urlencoded format. }
The abstract class URLStreamHandler is the common superclass for all stream protocol handlers. A stream protocol handler knows how to make a connection for a particular protocol type, such as http, ftp, or gopher.
public abstract class java.net.URLStreamHandler extends java.lang.Object { // Constructors public URLStreamHandler(); // The default constructor. // Methods protected abstract URLConnection openConnection(URL u); /* Opens a connection to the object referenced by the URL argument. Returns: a URLConnection object for the URL. Throws : IOException, if an IO error occurs while opening the conection. */ protected void parseURL(URL u, String spec, int start, int limit); /* Parses the string representation of a URL into a URL object. limit - the character position to stop parsing at. This is the end of the string or the position of the "#" character, if present. */ protected void setURL(URL u, String protocol, String host, int port,String file, String ref); // Sets the fields of the URL argument to the indicated values. protected String toExternalForm(URL u); // Converts a URL of a specific protocol to a String. }
This interface defines a factory for content handlers. This interface is used by the URLStreamHandler class to create a ContentHandler for a MIME type. An implemention of this interface should map a MIME type into an instance of ContentHandler.
public interface java.net.ContentHandlerFactory { // Methods public abstract ContentHandler createContentHandler(String mimetype); // Creates a new ContentHandler to read an object from a URLStreamHandler. }
This interface defines a factory for socket implementations. It is used by the classes Socket and ServerSocket to create actual socket implementions.
public interface java.net.SocketImplFactory { // Methods public abstract SocketImpl createSocketImpl(); // Returns : a new instance of SocketImpl. }
This interface defines a factory for URL stream protocol handlers. It is used by the URL class to create a URLStreamHandler for a specific protocol.
public interface java.net.URLStreamHandlerFactory { // Methods public abstract URLStreamHandler createURLStreamHandler(String protocol); // Returns : a URLStreamHandler for the specific protocol like "ftp", "http", "nntp", etc. }
Thrown to indicate than there is an error in the underlying protocol, such as a TCP error.
public class java.net.ProtocolException extends java.io.IOException { // Constructors public ProtocolException(); // Constructs a new ProtocolException with no detail message. public ProtocolException(String host); // Constructs a new ProtocolException with the specified detail message. }
Thrown to indicate that some error occurred while attempting to use a socket.
public class java.net.SocketException extends java.io.IOException { // Constructors public SocketException(); // Constructs a new SocketException with no detail message. public SocketException(String msg); // Constructs a new SocketException with the specified detail message. }
Thrown to indicate that the IP address of a host could not be determined.
public class java.net.UnknownHostException extends java.io.IOException { // Constructors public UnknownHostException(); // Constructs a new UnknownHostException with no detail message. public UnknownHostException(String host); // Constructs a new UnknownHostException with the specified detail message. }
Thrown to indicate that an unknown service exception has occurred. Either the MIME type returned by a URL connection does not make sense, or the application is attempting to write to a read-only URL connection.
public class java.net.UnknownServiceException extends java.io.IOException { // Constructors public UnknownServiceException(); // Constructs a new UnknownServiceException with no detail message. public UnknownServiceException(String msg); // Constructs a new UnknownServiceException with the specified detail message. }