How Tomcat Works

The ServerSocket Class

The Socket class represents a "client" socket, i.e. a socket that you construct whenever you want to connect to a remote server application. Now, if you want to implement a server application, such as an HTTP server or an FTP server, you need a different approach. This is because your server must stand by all the time as it does not know when a client application will try to connect to it. In order for your application to be able to stand by all the time, you need to use the java.net.ServerSocket class. This is an implementation of a server socket.

ServerSocket is different from Socket. The role of a server socket is to wait for connection requests from clients. Once the server socket gets a connection request, it creates a Socket instance to handle the communication with the client.

To create a server socket, you need to use one of the four constructors the ServerSocket class provides. You need to specify the IP address and port number the server socket will be listening on. Typically, the IP address will be 127.0.0.1, meaning that the server socket will be listening on the local machine. The IP address the server socket is listening on is referred to as the binding address. Another important property of a server socket is its backlog, which is the maximum queue length of incoming connection requests before the server socket starts to refuse the incoming requests.

One of the constructors of the ServerSocket class has the following signature:

public ServerSocket(int port, int backLog, InetAddress bindingAddress);

Notice that for this constructor, the binding address must be an instance of java.net.InetAddress. An easy way to construct an InetAddress object is by calling its static method getByName, passing a String containing the host name, such as in the following code.

InetAddress.getByName("127.0.0.1");

The following line of code constructs a ServerSocket that listens on port 8080 of the local machine. The ServerSocket has a backlog of 1.

new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));

Once you have a ServerSocket instance, you can tell it to wait for an incoming connection request to the binding address at the port the server socket is listening on. You do this by calling the ServerSocket class's accept method. This method will only return when there is a connection request and its return value is an instance of the Socket class. This Socket object can then be used to send and receive byte streams from the client application, as explained in the previous section, "The Socket Class". Practically, the accept method is the only method used in the application accompanying this chapter.