The java.net.Socket class

The java.net.Socket class allows you to perform all four fundamental socket operations. You can connect to remote machines; you can send data; you can receive data; you can close the connection.

Connection is accomplished through the constructors. Each Socket object is associated with exactly one remote host. To connect to a different host, you must create a new Socket object.

 public Socket(String host, int port) 
 throws UnknownHostException, IOException
public Socket(InetAddress address, int port) throws IOException
public Socket(String host, int port, InetAddress localAddress, 
 int localPort) throws IOException
public Socket(InetAddress address, int port, InetAddress localAddress, 
  int localPort)  throws IOException

Sending and receiving data is accomplished with output and input streams. There are methods to get an input stream for a socket and an output stream for the socket.

 public InputStream  getInputStream() throws IOException
 public OutputStream getOutputStream() throws IOException

There's a method to close a socket.

public void close() throws IOException

There are also methods to set various socket options. Most of the time the defaults are fine.

 public void    setTcpNoDelay(boolean on) throws SocketException
 public boolean getTcpNoDelay() throws SocketException
 public void    setSoLinger(boolean on, int val) throws SocketException
 public int     getSoLinger() throws SocketException
 public void    setSoTimeout(int timeout) throws SocketException
 public int     getSoTimeout() throws SocketException
 
 public static  void setSocketImplFactory(SocketImplFactory fac) 
  throws IOException

There are methods to return information about the socket:

 public InetAddress getInetAddress()
 public InetAddress getLocalAddress()
 public int         getPort()
 public int         getLocalPort()

Finally there's the usual toString() method:

 public String toString()

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified November 19, 1998