The java.net.ServerSocket Class

The java.net.ServerSocket class represents a server socket. It is constructed on a particular port. Then it calls accept() to listen for incoming connections. accept() blocks until a connection is detected. Then accept() returns a java.net.Socket object you use to perform the actual communication with the client.

There are three constructors that let you specify the port to bind to, the queue length for incoming connections, and the IP address to bind to:

 public ServerSocket(int port) throws IOException
 public ServerSocket(int port, int backlog) throws IOException
 public ServerSocket(int port, int backlog, InetAddress bindAddr) 
  throws IOException

The accept() and close() methods provide the basic functionality of a server socket.

 public Socket accept() throws IOException
 public void close() throws IOException

On a server with multiple IP addresses, the getInetAddress() method tells you which one this server socket is listening to. The getLocalPort() method tells you which port you're listening to.

 public InetAddress getInetAddress()
 public int getLocalPort()

There are three methods to set and get various options. The defaults are generally fine.

 public void setSoTimeout(int timeout) throws SocketException
 public int getSoTimeout() throws IOException
 public static void setSocketFactory(SocketImplFactory fac) 
  throws IOException

Finally, there's the usual toString() method:

 public String toString()

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified December 28, 1997