home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Book Home Java Enterprise in a Nutshell Search this book

Chapter 16. The java.net Package

The java.net package provides a powerful and flexible infrastructure for networking. Figure 16-1 and Figure 16-2 show the class hierarchy for this package. Many of the classes in this package are part of the networking infrastructure and are not used by normal applications; these complicated classes can make the package a difficult one to understand. In this overview, I describe only the classes an application might normally use.

figure

Figure 16-1. The classes of the java.net package

figure

Figure 16-2. The exceptions of the java.net package

The URL class represents an Internet uniform resource locator (URL). It provides a very simple interface to networking: the object referred to by the URL can be downloaded with a single call, or streams may be opened to read from or write to the object. At a slightly more complex level, a URLConnection object can be obtained from a given URL object. The URLConnection class provides additional methods that allow you to work with URLs in more sophisticated ways.

If you want to do more than simply download an object referenced by a URL, you can do your own networking with the Socket class. This class allows you to connect to a specified port on a specified Internet host and read and write data using the InputStream and OutputStream classes of the java.io package. If you want to implement a server to accept connections from clients, you can use the related ServerSocket class. Both Socket and ServerSocket use the InetAddress address class, which represents an Internet address.

The java.net package allows you to do low-level networking with DatagramPacket objects, which may be sent and received over the network through a DatagramSocket object. As of Java 1.1, the package has been extended to include a MulticastSocket class that supports multicast networking.

AuthenticatorJava 1.2
java.net

This abstract class defines a customizable mechanism for requesting and performing password authentication. The static setDefault() method establishes the systemwide Authenticator object to use when password authentication is requested. The implementation can obtain the required authentication information from the user however it wants (e.g., through a text- or a GUI-based interface). setDefault() can be called only once; subsequent calls are ignored. Calling setDefault() requires an appropriate NetPermission.

When an application or the Java runtime system requires password authentication (to read the contents of a specified URL, for example), it calls the static requestPasswordAuthentication() method, passing arguments that specify the host and port for which the password is required and a prompt that may be displayed to the user. This method looks up the default Authenticator for the system and calls its getPasswordAuthentication() method. Calling requestPasswordAuthentication() requires an appropriate NetPermission.

Authenticator is an abstract class; its default implementation of getPasswordAuthentication() always returns null. To create an Authenticator, you must override this method so that it prompts the user to enter a username and password and returns that information in the form of a PasswordAuthentication object. Your implementation of getPasswordAuthentication() may call the various getRequesting() methods to find who is requesting the password and what the recommended user prompt is.

public abstract class Authenticator {
// Public Constructors
public Authenticator ();
// Public Class Methods
public static PasswordAuthentication requestPasswordAuthentication (InetAddress addr, int port, String protocol, String prompt, String scheme);
public static void setDefault (Authenticator a); synchronized
// Protected Instance Methods
protected PasswordAuthentication getPasswordAuthentication (); constant
protected final int getRequestingPort ();
protected final String getRequestingPrompt ();
protected final String getRequestingProtocol ();
protected final String getRequestingScheme ();
protected final InetAddress getRequestingSite ();
}

Passed To: Authenticator.setDefault()

BindExceptionJava 1.1
java.netserializable checked PJ1.1

Signals that a socket cannot be bound to a local address and port. This often means that the port is already in use.

public class BindException extends SocketException {
// Public Constructors
public BindException ();
public BindException (String msg);
}

Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->SocketException-->BindException

ConnectExceptionJava 1.1
java.netserializable checked PJ1.1

Signals that a socket cannot be connected to a remote address and port. This means that the remote host can be reached, but is not responding, perhaps because there is no process on that host that is listening on the specified port.

public class ConnectException extends SocketException {
// Public Constructors
public ConnectException ();
public ConnectException (String msg);
}

Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->SocketException-->java.net.ConnectException

ContentHandlerJava 1.0
java.netPJ1.1

This abstract class defines a method that reads data from a URLConnection and returns an object that represents that data. Each subclass that implements this method is responsible for handling a different type of content (i.e., a different MIME type). Applications never create ContentHandler objects directly; they are created, when necessary, by the registered ContentHandlerFactory object. Applications should also never call ContentHandler methods directly; they should call URL.getContent() or URLConnection.getContent() instead. You need to subclass ContentHandler only if you are writing a web browser or similar application that needs to parse and understand some new content type.

public abstract class ContentHandler {
// Public Constructors
public ContentHandler ();
// Public Instance Methods
public abstract Object getContent (URLConnection urlc) throws java.io.IOException;
1.3public Object getContent (URLConnection urlc, Class[ ] classes) throws java.io.IOException;
}

Returned By: ContentHandlerFactory.createContentHandler()

ContentHandlerFactoryJava 1.0
java.netPJ1.1

This interface defines a method that creates and returns an appropriate ContentHandler object for a specified MIME type. A systemwide ContentHandlerFactory interface may be specified using the URLConnection.setContentHandlerFactory() method. Normal applications never need to use or implement this interface.

public interface ContentHandlerFactory {
// Public Instance Methods
public abstract ContentHandler createContentHandler (String mimetype);
}

Passed To: URLConnection.setContentHandlerFactory()

DatagramPacketJava 1.0
java.netPJ1.1

This class implements a packet of data that may be sent or received over the network through a DatagramSocket. One of the DatagramPacket constructors specifies an array of binary data to be sent with its destination address and port. A packet created with this constructor can then be sent with the send() method of a DatagramSocket. The other DatagramPacket constructor specifies an array of bytes into which data should be received. The receive() method of DatagramSocket waits for data and stores it in a DatagramPacket created in this way. The contents and sender of a received packet can be queried with the DatagramPacket instance methods.

public final class DatagramPacket {
// Public Constructors
public DatagramPacket (byte[ ] buf, int length);
1.2public DatagramPacket (byte[ ] buf, int offset, int length);
public DatagramPacket (byte[ ] buf, int length, InetAddress address, int port);
1.2public DatagramPacket (byte[ ] buf, int offset, int length, InetAddress address, int port);
// Property Accessor Methods (by property name)
public InetAddress getAddress (); synchronized
1.1public void setAddress (InetAddress iaddr); synchronized
public byte[ ] getData (); synchronized
1.1public void setData (byte[ ] buf); synchronized
1.2public void setData (byte[ ] buf, int offset, int length); synchronized
public int getLength (); synchronized
1.1public void setLength (int length); synchronized
1.2public int getOffset (); synchronized
public int getPort (); synchronized
1.1public void setPort (int iport); synchronized
}

Passed To: DatagramSocket.{receive(), send()}, DatagramSocketImpl.{receive(), send()}, MulticastSocket.send()

DatagramSocketJava 1.0
java.netPJ1.1

This class defines a socket that can receive and send unreliable datagram packets over the network using the UDP protocol. A datagram is a very low-level networking interface: it is simply an array of bytes sent over the network. A datagram does not implement any kind of stream-based communication protocol, and there is no connection established between the sender and the receiver. Datagram packets are called "unreliable" because the protocol does not make any attempt to ensure they arrive or to resend them if they don't. Thus, packets sent through a DatagramSocket are not guaranteed to arrive in the order sent or even to arrive at all. On the other hand, this low-overhead protocol makes datagram transmission very fast. See Socket and URL for higher-level interfaces to networking.

If a port is specified when the DatagramSocket is created, that port is used for sending and receiving datagrams; otherwise, the system assigns a port. getLocalPort() returns the port number in use. send() sends a DatagramPacket through the socket. The packet must contain the destination address to which it should be sent. receive() waits for data to arrive at the socket and stores it, along with the address of the sender, in the specified DatagramPacket. close() closes the socket and frees the port for reuse. Once close() has been called, the DatagramSocket should not be used again.

Each time a packet is sent or received, the system must perform a security check to ensure that the calling code has permission to send data to or receive data from the specified host. In Java 1.2 and later, if you are sending multiple packets to or receiving multiple packets from a single host, use connect() to specify the host with which you are communicating. This causes the security check to be done a single time, but does not allow the socket to communicate with any other host until disconnect() is called. Use getInetAddress() and getPort() to obtain the host and port, if any, the socket is connected to.

setSoTimeout() specifies the number of milliseconds that receive() waits for a packet to arrive before throwing an InterruptedIOException. Specify 0 milliseconds to wait forever. setSendBufferSize() and setReceiveBufferSize() set hints as to the underlying size of the networking buffers.

public class DatagramSocket {
// Public Constructors
public DatagramSocket () throws SocketException;
public DatagramSocket (int port) throws SocketException;
1.1public DatagramSocket (int port, InetAddress laddr) throws SocketException;
// Public Class Methods
1.3public static void setDatagramSocketImplFactory (DatagramSocketImplFactory fac) throws java.io.IOException; synchronized
// Property Accessor Methods (by property name)
1.2public InetAddress getInetAddress (); default:null
1.1public InetAddress getLocalAddress ();
public int getLocalPort (); default:1029
1.2public int getPort (); default:-1
1.2public int getReceiveBufferSize () throws SocketException; synchronized default:8192
1.2public void setReceiveBufferSize (int size) throws SocketException; synchronized
1.2public int getSendBufferSize () throws SocketException; synchronized default:8192
1.2public void setSendBufferSize (int size) throws SocketException; synchronized
1.1public int getSoTimeout () throws SocketException; synchronized default:0
1.1public void setSoTimeout (int timeout) throws SocketException; synchronized
// Public Instance Methods
public void close ();
1.2public void connect (InetAddress address, int port);
1.2public void disconnect ();
public void receive (DatagramPacket p) throws java.io.IOException; synchronized
public void send (DatagramPacket p) throws java.io.IOException;
}

Subclasses: MulticastSocket

DatagramSocketImplJava 1.1
java.netPJ1.1

This abstract class defines the methods necessary to implement communication through datagram and multicast sockets. System programmers may create subclasses of this class when they need to implement datagram or multicast sockets in a nonstandard network environment, such as behind a firewall or on a network that uses a nonstandard transport protocol. Normal applications never need to use or subclass this class.

public abstract class DatagramSocketImpl implements SocketOptions {
// Public Constructors
public DatagramSocketImpl ();
// Methods Implementing SocketOptions
public abstract Object getOption (int optID) throws SocketException;
public abstract void setOption (int optID, Object value) throws SocketException;
// Protected Instance Methods
protected abstract void bind (int lport, InetAddress laddr) throws SocketException;
protected abstract void close ();
protected abstract void create () throws SocketException;
protected java.io.FileDescriptor getFileDescriptor ();
protected int getLocalPort ();
1.2protected abstract int getTimeToLive () throws java.io.IOException;
protected abstract void join (InetAddress inetaddr) throws java.io.IOException;
protected abstract void leave (InetAddress inetaddr) throws java.io.IOException;
protected abstract int peek (InetAddress i) throws java.io.IOException;
protected abstract void receive (DatagramPacket p) throws java.io.IOException;
protected abstract void send (DatagramPacket p) throws java.io.IOException;
1.2protected abstract void setTimeToLive (int ttl) throws java.io.IOException;
// Protected Instance Fields
protected java.io.FileDescriptor fd ;
protected int localPort ;
// Deprecated Protected Methods
#protected abstract byte getTTL () throws java.io.IOException;
#protected abstract void setTTL (byte ttl) throws java.io.IOException;
}

Hierarchy: Object-->DatagramSocketImpl(SocketOptions)

Returned By: DatagramSocketImplFactory.createDatagramSocketImpl()

DatagramSocketImplFactoryJava 1.3 Beta
java.net

This interface defines a method that creates DatagramSocketImpl objects. You can register an instance of this factory interface with the static setDatagramSocketImplFactory() method of DatagramSocket. Application-level code never needs to use or implement this interface.

public interface DatagramSocketImplFactory {
// Public Instance Methods
public abstract DatagramSocketImpl createDatagramSocketImpl ();
}

Passed To: DatagramSocket.setDatagramSocketImplFactory()

FileNameMapJava 1.1
java.netPJ1.1

This interface defines a single method that is called to obtain the MIME type of a file based on the name of the file. The fileNameMap field of the URLConnection class refers to an object that implements this interface. The filename-to-file-type map it implements is used by the static URLConnection.guessContentTypeFromName() method.

public interface FileNameMap {
// Public Instance Methods
public abstract String getContentTypeFor (String fileName);
}

Passed To: URLConnection.setFileNameMap()

Returned By: URLConnection.getFileNameMap()

HttpURLConnectionJava 1.1
java.netPJ1.1

This class is a specialization of URLConnection. An instance of this class is returned when the openConnection() method is called for a URL object that uses the HTTP protocol. The many constants defined by this class are the status codes returned by HTTP servers. setRequestMethod() specifies what kind of HTTP request is made. The contents of this request must be sent through the OutputStream returned by the getOutputStream() method of the superclass. Once an HTTP request has been sent, getResponseCode() returns the HTTP server's response code as an integer, and getResponseMessage() returns the server's response message. The disconnect() method closes the connection. The static setFollowRedirects() specifies whether URL connections that use the HTTP protocol should automatically follow redirect responses sent by HTTP servers. In order to successfully use this class, you need to understand the details of the HTTP protocol.

public abstract class HttpURLConnection extends URLConnection {
// Protected Constructors
protected HttpURLConnection (URL u);
// Public Constants
public static final int HTTP_ACCEPTED ; =202
public static final int HTTP_BAD_GATEWAY ; =502
public static final int HTTP_BAD_METHOD ; =405
public static final int HTTP_BAD_REQUEST ; =400
public static final int HTTP_CLIENT_TIMEOUT ; =408
public static final int HTTP_CONFLICT ; =409
public static final int HTTP_CREATED ; =201
public static final int HTTP_ENTITY_TOO_LARGE ; =413
public static final int HTTP_FORBIDDEN ; =403
public static final int HTTP_GATEWAY_TIMEOUT ; =504
public static final int HTTP_GONE ; =410
public static final int HTTP_INTERNAL_ERROR ; =500
public static final int HTTP_LENGTH_REQUIRED ; =411
public static final int HTTP_MOVED_PERM ; =301
public static final int HTTP_MOVED_TEMP ; =302
public static final int HTTP_MULT_CHOICE ; =300
public static final int HTTP_NO_CONTENT ; =204
public static final int HTTP_NOT_ACCEPTABLE ; =406
public static final int HTTP_NOT_AUTHORITATIVE ; =203
public static final int HTTP_NOT_FOUND ; =404
1.3public static final int HTTP_NOT_IMPLEMENTED ; =501
public static final int HTTP_NOT_MODIFIED ; =304
public static final int HTTP_OK ; =200
public static final int HTTP_PARTIAL ; =206
public static final int HTTP_PAYMENT_REQUIRED ; =402
public static final int HTTP_PRECON_FAILED ; =412
public static final int HTTP_PROXY_AUTH ; =407
public static final int HTTP_REQ_TOO_LONG ; =414
public static final int HTTP_RESET ; =205
public static final int HTTP_SEE_OTHER ; =303
public static final int HTTP_UNAUTHORIZED ; =401
public static final int HTTP_UNAVAILABLE ; =503
public static final int HTTP_UNSUPPORTED_TYPE ; =415
public static final int HTTP_USE_PROXY ; =305
public static final int HTTP_VERSION ; =505
// Public Class Methods
public static boolean getFollowRedirects ();
public static void setFollowRedirects (boolean set);
// Public Instance Methods
public abstract void disconnect ();
1.2public java.io.InputStream getErrorStream (); constant
public String getRequestMethod ();
public int getResponseCode () throws java.io.IOException;
public String getResponseMessage () throws java.io.IOException;
public void setRequestMethod (String method) throws ProtocolException;
public abstract boolean usingProxy ();
// Public Methods Overriding URLConnection
1.3public long getHeaderFieldDate (String name, long Default);
1.2public java.security.Permission getPermission () throws java.io.IOException;
// Protected Instance Fields
protected String method ;
protected int responseCode ;
protected String responseMessage ;
// Deprecated Public Fields
#public static final int HTTP_SERVER_ERROR ; =500
}

Hierarchy: Object-->URLConnection-->HttpURLConnection

InetAddressJava 1.0
java.netserializable PJ1.1

This class represents an Internet address and is used when creating DatagramPacket or Socket objects. The class does not have a public constructor function, but instead supports three static methods that return one or more instances of InetAddress. getLocalHost() returns an InetAddress for the local host. getByName() returns the InetAddress of a host specified by name. getAllByName() returns an array of InetAddress objects that represents all the available addresses for a host specified by name. Instance methods are getHostName(), which returns the hostname of an InetAddress, and getAddress(), which returns the Internet IP address as an array of bytes, with the highest-order byte as the first element of the array.

public final class InetAddress implements Serializable {
// No Constructor
// Public Class Methods
public static InetAddress[ ] getAllByName (String host) throws java.net.UnknownHostException;
public static InetAddress getByName (String host) throws java.net.UnknownHostException;
public static InetAddress getLocalHost () throws java.net.UnknownHostException; synchronized
// Property Accessor Methods (by property name)
public byte[ ] getAddress ();
public String getHostAddress ();
public String getHostName ();
1.1public boolean isMulticastAddress ();
// Public Methods Overriding Object
public boolean equals (Object obj);
public int hashCode ();
public String toString ();
}

Hierarchy: Object-->InetAddress(Serializable)

Passed To: Too many methods to list.

Returned By: Authenticator.getRequestingSite(), DatagramPacket.getAddress(), DatagramSocket.{getInetAddress(), getLocalAddress()}, InetAddress.{getAllByName(), getByName(), getLocalHost()}, MulticastSocket.getInterface(), ServerSocket.getInetAddress(), Socket.{getInetAddress(), getLocalAddress()}, SocketImpl.getInetAddress(), URLStreamHandler.getHostAddress()

Type Of: SocketImpl.address

JarURLConnectionJava 1.2
java.net

This class is a specialized URLConnection that represents a connection to a jar: URL. A jar: URL is a compound URL that includes the URL of a JAR archive and, optionally, a reference to a file or directory within the JAR archive. The jar: URL syntax uses the ! character to separate the pathname of the JAR archive from the filename within the JAR archive. Note that a jar: URL contains a subprotocol that specifies the protocol that retrieves the JAR file itself. For example:

jar:http://my.jar.com/my.jar!/                                   // The whole archive
jar:file:/usr/java/lib/my.jar!/com/jar/                      // A directory of the archive
jar:ftp://ftp.jar.com/pub/my.jar!/com/jar/Jar.class  // A file in the archive

To obtain a JarURLConnection, define a URL object for a jar: URL, open a connection to it with openConnection(), and cast the returned URLConnection object to a JarURLConnection. The various methods defined by JarURLConnection allow you to read the manifest file of the JAR archive and look up attributes from that manifest for the archive as a whole or for individual entries in the archive. These methods make use of various classes from the java.util.jar package.

public abstract class JarURLConnection extends URLConnection {
// Protected Constructors
protected JarURLConnection (URL url) throws MalformedURLException;
// Property Accessor Methods (by property name)
public java.util.jar.Attributes getAttributes () throws java.io.IOException;
public java.security.cert.Certificate[ ] getCertificates () throws java.io.IOException;
public String getEntryName ();
public java.util.jar.JarEntry getJarEntry () throws java.io.IOException;
public abstract java.util.jar.JarFile getJarFile () throws java.io.IOException;
public URL getJarFileURL ();
public java.util.jar.Attributes getMainAttributes () throws java.io.IOException;
public java.util.jar.Manifest getManifest () throws java.io.IOException;
// Protected Instance Fields
protected URLConnection jarFileURLConnection ;
}

Hierarchy: Object-->URLConnection-->JarURLConnection

MalformedURLExceptionJava 1.0
java.netserializable checked PJ1.1

Signals that an unparseable URL specification has been passed to a method.

public class MalformedURLException extends java.io.IOException {
// Public Constructors
public MalformedURLException ();
public MalformedURLException (String msg);
}

Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->MalformedURLException

Thrown By: Too many methods to list.

MulticastSocketJava 1.1
java.netPJ1.1

This subclass of DatagramSocket can send and receive multicast UDP packets. It extends DatagramSocket by adding joinGroup() and leaveGroup() methods to join and leave multicast groups. The IP address specified to these methods should be a valid multicast address in the range of 224.0.0.1 to 239.255.255.255. Note that you do not have to join a group to send a packet to a multicast address, but you must join the group to receive packets sent to that address. Note that untrusted code is not allowed to use multicast sockets.

MulticastSocket defines a variant send() method that allows you to specify a time-to-live (TTL) value for the packet you send. This value specifies the number of network hops the packet can travel before it expires. You can also set a default TTL for all packets sent though a MulticastSocket with setTimeToLive(), or, prior to Java 1.2, with setTTL().

public class MulticastSocket extends DatagramSocket {
// Public Constructors
public MulticastSocket () throws java.io.IOException;
public MulticastSocket (int port) throws java.io.IOException;
// Property Accessor Methods (by property name)
public InetAddress getInterface () throws SocketException;
public void setInterface (InetAddress inf) throws SocketException;
1.2public int getTimeToLive () throws java.io.IOException; default:1
1.2public void setTimeToLive (int ttl) throws java.io.IOException;
// Public Instance Methods
public void joinGroup (InetAddress mcastaddr) throws java.io.IOException;
public void leaveGroup (InetAddress mcastaddr) throws java.io.IOException;
public void send (DatagramPacket p, byte ttl) throws java.io.IOException;
// Deprecated Public Methods
#public byte getTTL () throws java.io.IOException; default:1
#public void setTTL (byte ttl) throws java.io.IOException;
}

Hierarchy: Object-->DatagramSocket-->MulticastSocket

NetPermissionJava 1.2
java.netserializable permission

This class is a java.security.Permission that represents various permissions required for Java's URL-based networking system. See also SocketPermission, which represents permissions to perform lower-level networking operations. A NetPermission is defined solely by its name; no actions list is required or supported. As of Java 1.2, there are three NetPermission targets defined: "setDefaultAuthenticator" is required to call Authenticator.setDefault(); "requestPasswordAuthentication" to call Authenticator.requestPasswordAuthentication(); and "specifyStreamHandler" to explicitly pass a URLStreamHandler object to the URL() constructor. The target "*" is a wildcard that represents all defined NetPermission targets.

System administrators configuring security policies must be familiar with this class and the permissions it represents. System programmers may use this class, but application programmers never need to use it explicitly.

public final class NetPermission extends java.security.BasicPermission {
// Public Constructors
public NetPermission (String name);
public NetPermission (String name, String actions);
}

Hierarchy: Object-->java.security.Permission(java.security.Guard,Serializable)-->java.security.BasicPermission(Serializable)-->NetPermission

NoRouteToHostExceptionJava 1.1
java.netserializable checked PJ1.1

This exception signals that a socket cannot be connected to a remote host because the host cannot be contacted. Typically, this means that some link in the network between the local machine and the remote host is down or that the host is behind a firewall.

public class NoRouteToHostException extends SocketException {
// Public Constructors
public NoRouteToHostException ();
public NoRouteToHostException (String msg);
}

Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->SocketException-->NoRouteToHostException

PasswordAuthenticationJava 1.2
java.net

This simple immutable class encapsulates a username and a password. The password is stored as a character array rather than as a String object so that the caller can erase the contents of the array after use for increased security. Note that the PasswordAuthentication() constructor clones the specified password character array, but getPassword() returns a reference to the object's internal array. Obtain a PasswordAuthentication object by calling Authenticator.requestPasswordAuthentication().

public final class PasswordAuthentication {
// Public Constructors
public PasswordAuthentication (String userName, char[ ] password);
// Public Instance Methods
public char[ ] getPassword ();
public String getUserName ();
}

Returned By: Authenticator.{getPasswordAuthentication(), requestPasswordAuthentication()}

ProtocolExceptionJava 1.0
java.netserializable checked PJ1.1

Signals a protocol error in the Socket class.

public class ProtocolException extends java.io.IOException {
// Public Constructors
public ProtocolException ();
public ProtocolException (String host);
}

Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->ProtocolException

Thrown By: HttpURLConnection.setRequestMethod()

ServerSocketJava 1.0
java.netPJ1.1

This class is used by servers to listen for connection requests from clients. When you create a ServerSocket, you specify the port to listen on. The accept() method begins listening on that port and blocks until a client requests a connection on the port. At that point, accept() accepts the connection, creating and returning a Socket the server can use to communicate with the client. A typical server starts a new thread to handle the communication with the client and calls accept() again to listen for another connection. If you do not want accept() to block for an indefinite amount of time, call setSoTimeout() to specify the number of milliseconds accept() should wait for a connection before throwing an InterruptedIOException.

public class ServerSocket {
// Public Constructors
public ServerSocket (int port) throws java.io.IOException;
public ServerSocket (int port, int backlog) throws java.io.IOException;
1.1public ServerSocket (int port, int backlog, InetAddress bindAddr) throws java.io.IOException;
// Public Class Methods
public static void setSocketFactory (SocketImplFactory fac) throws java.io.IOException; synchronized
// Property Accessor Methods (by property name)
public InetAddress getInetAddress ();
public int getLocalPort ();
1.1public int getSoTimeout () throws java.io.IOException; synchronized
1.1public void setSoTimeout (int timeout) throws SocketException; synchronized
// Public Instance Methods
public Socket accept () throws java.io.IOException;
public void close () throws java.io.IOException;
// Public Methods Overriding Object
public String toString ();
// Protected Instance Methods
1.1protected final void implAccept (Socket s) throws java.io.IOException;
}

Returned By: java.rmi.server.RMIServerSocketFactory.createServerSocket(), java.rmi.server.RMISocketFactory.createServerSocket()

SocketJava 1.0
java.netPJ1.1

This class implements a socket for stream-based interprocess communication over the network. See URL for a higher-level interface to networking and DatagramSocket for a lower-level interface.

Use the Socket() constructor to create a socket and connect it to the specified host and port. Once the socket is created, getInputStream() and getOutputStream() return InputStream and OutputStream objects you can use to communicate with the remote host, just as you would use them for file input and output. getInetAddress() and getPort() return the address and port to which the socket is connected. getLocalPort() returns the local port the socket is using. See ServerSocket for information about how a server can listen for and accept connections of this type. When you are done with a Socket, use close() to close it. In Java 1.3, you can also use shutdownInput() and shutdownOutput() to close the input and output communication channels individually.

There are several options you can specify for a Socket object to alter its behavior. setSendBufferSize() and setReceiveBufferSize() provide hints to the underlying networking system as to what buffer size is best to use with this socket. setSoTimeout() specifies the number of milliseconds a read() call on the input stream returned by getInputStream() waits for data before throwing an InterruptedIOException. The default value of 0 specifies that the stream blocks indefinitely. setSoLinger() specifies what to do when a socket is closed while there is still data waiting to be transmitted. If lingering is turned on, the close() call blocks for up to the specified number of seconds while attempting to transmit the remaining data. Calling setTcpNoDelay() with an argument of true causes data to be sent through the socket as soon as it is available, instead of waiting for the TCP packet to become more full before sending it. In Java 1.3, use setKeepAlive() to enable or disable the periodic exchange of control messages across an idle socket connection. The keepalive protocol enables a client to determine if its server has crashed without closing the socket and vice versa.

public class Socket {
// Public Constructors
public Socket (String host, int port) throws java.net.UnknownHostExceptionjava.io.IOException;
public Socket (InetAddress address, int port) throws java.io.IOException;
#public Socket (String host, int port, boolean stream) throws java.io.IOException;
#public Socket (InetAddress host, int port, boolean stream) throws java.io.IOException;
1.1public Socket (String host, int port, InetAddress localAddr, int localPort) throws java.io.IOException;
1.1public Socket (InetAddress address, int port, InetAddress localAddr, int localPort) throws java.io.IOException;
// Protected Constructors
protected Socket ();
1.1protected Socket (SocketImpl impl) throws SocketException;
// Public Class Methods
public static void setSocketImplFactory (SocketImplFactory fac) throws java.io.IOException; synchronized
// Property Accessor Methods (by property name)
public InetAddress getInetAddress ();
public java.io.InputStream getInputStream () throws java.io.IOException;
1.3public boolean getKeepAlive () throws SocketException;
1.3public void setKeepAlive (boolean on) throws SocketException;
1.1public InetAddress getLocalAddress ();
public int getLocalPort ();
public java.io.OutputStream getOutputStream () throws java.io.IOException;
public int getPort ();
1.2public int getReceiveBufferSize () throws SocketException; synchronized
1.2public void setReceiveBufferSize (int size) throws SocketException; synchronized
1.2public int getSendBufferSize () throws SocketException; synchronized
1.2public void setSendBufferSize (int size) throws SocketException; synchronized
1.1public int getSoLinger () throws SocketException;
1.1public int getSoTimeout () throws SocketException; synchronized
1.1public void setSoTimeout (int timeout) throws SocketException; synchronized
1.1public boolean getTcpNoDelay () throws SocketException;
1.1public void setTcpNoDelay (boolean on) throws SocketException;
// Public Instance Methods
public void close () throws java.io.IOException; synchronized
1.1public void setSoLinger (boolean on, int linger) throws SocketException;
1.3public void shutdownInput () throws java.io.IOException;
1.3public void shutdownOutput () throws java.io.IOException;
// Public Methods Overriding Object
public String toString ();
}

Passed To: ServerSocket.implAccept()

Returned By: ServerSocket.accept(), java.rmi.server.RMIClientSocketFactory.createSocket(), java.rmi.server.RMISocketFactory.createSocket()

SocketExceptionJava 1.0
java.netserializable checked PJ1.1

Signals an exceptional condition while using a socket.

public class SocketException extends java.io.IOException {
// Public Constructors
public SocketException ();
public SocketException (String msg);
}

Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->SocketException

Subclasses: BindException, java.net.ConnectException, NoRouteToHostException

Thrown By: Too many methods to list.

SocketImplJava 1.0
java.netPJ1.1

This abstract class defines the methods necessary to implement communication through sockets. Different subclasses of this class may provide different implementations suitable in different environments (such as behind firewalls). These socket implementations are used by the Socket and ServerSocket classes. Normal applications never need to use or subclass this class.

public abstract class SocketImpl implements SocketOptions {
// Public Constructors
public SocketImpl ();
// Methods Implementing SocketOptions
1.1public abstract Object getOption (int optID) throws SocketException;
1.1public abstract void setOption (int optID, Object value) throws SocketException;
// Public Methods Overriding Object
public String toString ();
// Protected Instance Methods
protected abstract void accept (SocketImpl s) throws java.io.IOException;
protected abstract int available () throws java.io.IOException;
protected abstract void bind (InetAddress host, int port) throws java.io.IOException;
protected abstract void close () throws java.io.IOException;
protected abstract void connect (String host, int port) throws java.io.IOException;
protected abstract void connect (InetAddress address, int port) throws java.io.IOException;
protected abstract void create (boolean stream) throws java.io.IOException;
protected java.io.FileDescriptor getFileDescriptor ();
protected InetAddress getInetAddress ();
protected abstract java.io.InputStream getInputStream () throws java.io.IOException;
protected int getLocalPort ();
protected abstract java.io.OutputStream getOutputStream () throws java.io.IOException;
protected int getPort ();
protected abstract void listen (int backlog) throws java.io.IOException;
1.3protected void shutdownInput () throws java.io.IOException;
1.3protected void shutdownOutput () throws java.io.IOException;
// Protected Instance Fields
protected InetAddress address ;
protected java.io.FileDescriptor fd ;
protected int localport ;
protected int port ;
}

Hierarchy: Object-->SocketImpl(SocketOptions)

Passed To: Socket.Socket(), SocketImpl.accept()

Returned By: SocketImplFactory.createSocketImpl()

SocketImplFactoryJava 1.0
java.netPJ1.1

This interface defines a method that creates SocketImpl objects. SocketImplFactory objects may be registered to create SocketImpl objects for the Socket and ServerSocket classes. Normal applications never need to use or implement this interface.

public interface SocketImplFactory {
// Public Instance Methods
public abstract SocketImpl createSocketImpl ();
}

Passed To: ServerSocket.setSocketFactory(), Socket.setSocketImplFactory()

SocketOptionsJava 1.2
java.net

This interface defines constants that represent low-level BSD Unix-style socket options and methods that set and query the value of those options. In Java 1.2, SocketImpl and DatagramSocketImpl implement this interface. Any custom socket implementations you define should also provide meaningful implementations for the getOption() and setOption() methods. Your implementation may support options other than those defined here. Only custom socket implementations need to use this interface. All other code can use methods defined by Socket, ServerSocket, DatagramSocket, and MulticastSocket to set specific socket options for those socket types.

public interface SocketOptions {
// Public Constants
public static final int IP_MULTICAST_IF ; =16
public static final int SO_BINDADDR ; =15
1.3public static final int SO_KEEPALIVE ; =8
public static final int SO_LINGER ; =128
public static final int SO_RCVBUF ; =4098
public static final int SO_REUSEADDR ; =4
public static final int SO_SNDBUF ; =4097
public static final int SO_TIMEOUT ; =4102
public static final int TCP_NODELAY ; =1
// Public Instance Methods
public abstract Object getOption (int optID) throws SocketException;
public abstract void setOption (int optID, Object value) throws SocketException;
}

Implementations: DatagramSocketImpl, SocketImpl

SocketPermissionJava 1.2
java.netserializable permission

This class is a java.security.Permission that governs all networking operations performed with sockets. Like all permissions, a SocketPermission consists of a name, or target, and a list of actions that may be performed on that target. The target of a SocketPermission is the host and, optionally, the port or ports for which permission is being granted or requested. The target consists of a hostname optionally followed by a colon and a port specification. The host may be a DNS domain name, a numerical IP address, or the string "localhost". If you specify a host domain name, you may use * as a wildcard as the leftmost portion of the hostname. The port specification, if present, must be a single port number or a range of port numbers in the form n1-n2. If n1 is omitted, it is taken to be 0, and if n2 is omitted, it is taken to be 65535. If no port is specified, the socket permission applies to all ports of the specified host. Here are some legal SocketPermission targets:

java.sun.com:80
*.sun.com:1024-2000
*:1024-
localhost:-1023

In addition to a target, each SocketPermission must have a comma-separated list of actions, which specify the operations that may be performed on the specified host(s) and port(s). The available actions are "connect", "accept", "listen", and "resolve". "connect" represents permission to connect to the specified target. "accept" indicates permission to accept connections from the specified target. "listen" represents permission to listen on the specified ports for connection requests. This action is only valid when used for ports on "localhost". Finally, the "resolve" action indicates permission to use the DNS name service to resolve domain names into IP addresses. This action is required for and implied by all other actions.

System administrators configuring security policies must be familiar with this class and understand the risks of granting the various permissions it represents. System programmers writing new low-level networking libraries or connecting to native code that performs networking may need to use this class. Application programmers, however, should never need to use it directly.

public final class SocketPermission extends java.security.Permission implements Serializable {
// Public Constructors
public SocketPermission (String host, String action);
// Public Methods Overriding Permission
public boolean equals (Object obj);
public String getActions ();
public int hashCode ();
public boolean implies (java.security.Permission p);
public java.security.PermissionCollection newPermissionCollection ();
}

Hierarchy: Object-->java.security.Permission(java.security.Guard,Serializable)-->SocketPermission(Serializable)

UnknownHostExceptionJava 1.0
java.netserializable checked PJ1.1

Signals that the name of a specified host could not be resolved.

public class UnknownHostException extends java.io.IOException {
// Public Constructors
public UnknownHostException ();
public UnknownHostException (String host);
}

Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->java.net.UnknownHostException

Thrown By: InetAddress.{getAllByName(), getByName(), getLocalHost()}, Socket.Socket()

UnknownServiceExceptionJava 1.0
java.netserializable checked PJ1.1

Signals an attempt to use an unsupported service of a network connection.

public class UnknownServiceException extends java.io.IOException {
// Public Constructors
public UnknownServiceException ();
public UnknownServiceException (String msg);
}

Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->UnknownServiceException

URLJava 1.0
java.netserializable PJ1.1

This class represents a uniform resource locator and allows the data referred to by the URL to be downloaded. A URL can be specified as a single string or with separate protocol, host, port, and file specifications. Relative URLs can also be specified with a String and the URL object to which it is relative. getFile(), getHost(), getPort(), getProtocol(), and getRef() return the various portions of the URL specified by a URL object. sameFile() determines whether a URL object refers to the same file as this one. The data or object referred to by a URL can be downloaded from the Internet in three ways: with a URLConnection created with openConnection(), with an InputStream created by openStream(), or with getContent(), which returns the URL contents directly if an appropriate ContentHandler can be found.

public final class URL implements Serializable {
// Public Constructors
public URL (String spec) throws MalformedURLException;
public URL (URL context, String spec) throws MalformedURLException;
1.2public URL (URL context, String spec, URLStreamHandler handler) throws MalformedURLException;
public URL (String protocol, String host, String file) throws MalformedURLException;
public URL (String protocol, String host, int port, String file) throws MalformedURLException;
1.2public URL (String protocol, String host, int port, String file, URLStreamHandler handler) throws MalformedURLException;
// Public Class Methods
public static void setURLStreamHandlerFactory (URLStreamHandlerFactory fac); synchronized
// Property Accessor Methods (by property name)
1.3public String getAuthority ();
public final Object getContent () throws java.io.IOException;
1.3public final Object getContent (Class[ ] classes) throws java.io.IOException;
public String getFile ();
public String getHost ();
1.3public String getPath ();
public int getPort ();
public String getProtocol ();
1.3public String getQuery ();
public String getRef ();
1.3public String getUserInfo ();
// Public Instance Methods
public URLConnection openConnection () throws java.io.IOException;
public final java.io.InputStream openStream () throws java.io.IOException;
public boolean sameFile (URL other);
public String toExternalForm ();
// Public Methods Overriding Object
public boolean equals (Object obj);
public int hashCode (); synchronized
public String toString ();
// Protected Instance Methods
protected void set (String protocol, String host, int port, String file, String ref);
1.3protected void set (String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref);
}

Hierarchy: Object-->URL(Serializable)

Passed To: Too many methods to list.

Returned By: Too many methods to list.

Type Of: URLConnection.url

URLClassLoaderJava 1.2
java.net

This ClassLoader provides a useful way to load untrusted Java code from a search path of arbitrary URLs, where each URL represents a directory or JAR file to search. Use the inherited loadClass() method to load a named class with a URLClassLoader. Classes loaded by a URLClassLoader have whatever permissions are granted to their java.security.CodeSource by the system java.security.Policy, plus they have one additional permission that allows the class loader to read any resource files associated with the class. If the class is loaded from a local file: URL that represents a directory, the class is given permission to read all files and directories below that directory. If the class is loaded from a local file: URL that represents a JAR file, the class is given permission to read that JAR file. If the class is loaded from a URL that represents a resource on another host, that class is given permission to connect to and accept network connections from that host. Note, however, that loaded classes are not granted this additional permission if the code that created the URLClassLoader in the first place would not have had that permission.

You can obtain a URLClassLoader by calling one of the URLClassLoader() constructors or one of the static newInstance() methods. If you call newInstance(), the loadClass() method of the returned URLClassLoader performs an additional check to ensure that the caller has permission to access the specified package.

public class URLClassLoader extends java.security.SecureClassLoader {
// Public Constructors
public URLClassLoader (URL[ ] urls);
public URLClassLoader (URL[ ] urls, ClassLoader parent);
public URLClassLoader (URL[ ] urls, ClassLoader parent, URLStreamHandlerFactory factory);
// Public Class Methods
public static URLClassLoader newInstance (URL[ ] urls);
public static URLClassLoader newInstance (URL[ ] urls, ClassLoader parent);
// Public Instance Methods
public URL[ ] getURLs ();
// Protected Methods Overriding SecureClassLoader
protected java.security.PermissionCollection getPermissions (java.security.CodeSource codesource);
// Public Methods Overriding ClassLoader
public URL findResource (String name);
public java.util.Enumeration findResources (String name) throws java.io.IOException;
// Protected Methods Overriding ClassLoader
protected Class findClass (String name) throws ClassNotFoundException;
// Protected Instance Methods
protected void addURL (URL url);
protected Package definePackage (String name, java.util.jar.Manifest man, URL url) throws IllegalArgumentException;
}

Hierarchy: Object-->ClassLoader-->java.security.SecureClassLoader-->URLClassLoader

Returned By: URLClassLoader.newInstance()

URLConnectionJava 1.0
java.netPJ1.1

This abstract class defines a network connection to an object specified by a URL. URL.openConnection() returns a URLConnection instance. You should use a URLConnection object when you want more control over the downloading of data than is available through the simpler URL methods. connect() actually makes the network connection. Other methods that depend on being connected call this method. getContent() returns the data referred to by the URL, parsed into an appropriate type of Object. If the URL protocol supports read and write operations, getInputStream() and getOutputStream() return input and output streams to the object referred to by the URL, respectively. getContentLength(), getContentType(), getContentEncoding(), getExpiration(), getDate(), and getLastModified() return the appropriate information about the object referred to by the URL, if that information can be determined (e.g., from HTTP header fields). getHeaderField() returns an HTTP header field specified by name or by number. getHeaderFieldInt() and getHeaderFieldDate() return the value of a named header field parsed as an integer or a date.

There are a number of options you can specify to control how the URLConnection behaves. These options are set with the various set() methods and may be queried with corresponding get() methods. The options must be set before the connect() method is called. setDoInput() and setDoOutput() allow you to specify whether you are using the URLConnection for input and/or output (input-only by default). setAllowUserInteraction() specifies whether user interaction (such as typing a password) is allowed during the data transfer (false by default). setDefaultAllowUserInteraction() is a class method that allows you to change the default value for user interaction. setUseCaches() allows you to specify whether a cached version of the URL can be used. You can set this to false to force a URL to be reloaded. setDefaultUseCaches() sets the default value for setUseCaches(). setIfModifiedSince() allows you to specify that a URL should not be fetched unless it has been modified since a specified time (if it is possible to determine its modification date).

public abstract class URLConnection {
// Protected Constructors
protected URLConnection (URL url);
// Public Class Methods
public static boolean getDefaultAllowUserInteraction ();
1.1public static FileNameMap getFileNameMap (); synchronized
public static String guessContentTypeFromStream (java.io.InputStream is) throws java.io.IOException;
public static void setContentHandlerFactory (ContentHandlerFactory fac); synchronized
public static void setDefaultAllowUserInteraction (boolean defaultallowuserinteraction);
1.1public static void setFileNameMap (FileNameMap map);
// Protected Class Methods
protected static String guessContentTypeFromName (String fname);
// Property Accessor Methods (by property name)
public boolean getAllowUserInteraction ();
public void setAllowUserInteraction (boolean allowuserinteraction);
public Object getContent () throws java.io.IOException;
1.3public Object getContent (Class[ ] classes) throws java.io.IOException;
public String getContentEncoding ();
public int getContentLength ();
public String getContentType ();
public long getDate ();
public boolean getDefaultUseCaches ();
public void setDefaultUseCaches (boolean defaultusecaches);
public boolean getDoInput ();
public void setDoInput (boolean doinput);
public boolean getDoOutput ();
public void setDoOutput (boolean dooutput);
public long getExpiration ();
public long getIfModifiedSince ();
public void setIfModifiedSince (long ifmodifiedsince);
public java.io.InputStream getInputStream () throws java.io.IOException;
public long getLastModified ();
public java.io.OutputStream getOutputStream () throws java.io.IOException;
1.2public java.security.Permission getPermission () throws java.io.IOException;
public URL getURL ();
public boolean getUseCaches ();
public void setUseCaches (boolean usecaches);
// Public Instance Methods
public abstract void connect () throws java.io.IOException;
public String getHeaderField (int n); constant
public String getHeaderField (String name); constant
public long getHeaderFieldDate (String name, long Default);
public int getHeaderFieldInt (String name, int Default);
public String getHeaderFieldKey (int n); constant
public String getRequestProperty (String key);
public void setRequestProperty (String key, String value);
// Public Methods Overriding Object
public String toString ();
// Protected Instance Fields
protected boolean allowUserInteraction ;
protected boolean connected ;
protected boolean doInput ;
protected boolean doOutput ;
protected long ifModifiedSince ;
protected URL url ;
protected boolean useCaches ;
// Deprecated Public Methods
#public static String getDefaultRequestProperty (String key); constant
#public static void setDefaultRequestProperty (String key, String value); empty
}

Subclasses: HttpURLConnection, JarURLConnection

Passed To: ContentHandler.getContent()

Returned By: URL.openConnection(), URLStreamHandler.openConnection()

Type Of: JarURLConnection.jarFileURLConnection

URLDecoderJava 1.2
java.net

This class defines a static decode() method that reverses the encoding performed by URLEncoder.encode(). It decodes 8-bit text with the MIME type "x-www-form-urlencoded", which is a standard encoding used by web browsers to submit form contents to CGI scripts and other server-side programs.

public class URLDecoder {
// Public Constructors
public URLDecoder ();
// Public Class Methods
public static String decode (String s);
}
URLEncoderJava 1.0
java.netPJ1.1

This class defines a single static method that converts a string to its URL-encoded form. That is, spaces are converted to +, and nonalphanumeric characters other than underscore are output as two hexadecimal digits following a percent sign. Note that this technique works only for 8-bit characters. This method canonicalizes a URL specification so that it uses only characters from an extremely portable subset of ASCII that can be correctly handled by computers around the world.

public class URLEncoder {
// No Constructor
// Public Class Methods
public static String encode (String s);
}
URLStreamHandlerJava 1.0
java.netPJ1.1

This abstract class defines the openConnection() method that creates a URLConnection for a given URL. A separate subclass of this class may be defined for various URL protocol types. A URLStreamHandler is created by a URLStreamHandlerFactory. Normal applications never need to use or subclass this class.

public abstract class URLStreamHandler {
// Public Constructors
public URLStreamHandler ();
// Protected Instance Methods
1.3protected boolean equals (URL u1, URL u2);
1.3protected int getDefaultPort (); constant
1.3protected InetAddress getHostAddress (URL u); synchronized
1.3protected int hashCode (URL u);
1.3protected boolean hostsEqual (URL u1, URL u2);
protected abstract URLConnection openConnection (URL u) throws java.io.IOException;
protected void parseURL (URL u, String spec, int start, int limit);
1.3protected boolean sameFile (URL u1, URL u2);
1.3protected void setURL (URL u, String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref);
protected String toExternalForm (URL u);
// Deprecated Protected Methods
#protected void setURL (URL u, String protocol, String host, int port, String file, String ref);
}

Passed To: URL.URL()

Returned By: URLStreamHandlerFactory.createURLStreamHandler()

URLStreamHandlerFactoryJava 1.0
java.netPJ1.1

This interface defines a method that creates a URLStreamHandler object for a specified protocol. Normal applications never need to use or implement this interface.

public interface URLStreamHandlerFactory {
// Public Instance Methods
public abstract URLStreamHandler createURLStreamHandler (String protocol);
}

Passed To: URL.setURLStreamHandlerFactory(), URLClassLoader.URLClassLoader()



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.







??????????????@Mail.ru