O'Reilly logo

Java RMI by William Grosso

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

ServerSockets

So far, we’ve focused on how to write a client program using sockets. Our example code assumed that a server application was already running, and the server was accepting connections on a well-known port. The next logical step in our discussion of sockets is to write an application that will accept connections. Fortunately, this isn’t much more complicated than creating a client application. The steps are:

  1. Create an instance of ServerSocket . As part of doing so, you will supply a port on which ServerSocket listens for connections.

  2. Call the accept( ) method of ServerSocket.Once you do this, the server program simply waits for client connections.

The accept( ) method

The key to using ServerSocket is the accept( ) method. It has the following signature:

public Socket accept(  ) throws IOException

There are two important facts to note about accept( ). The first is that accept( ) is a blocking method. If a client never attempts to connect to the server, the server will sit and wait inside the accept( ) method. This means that the code that follows the call to the accept( ) method will never execute.

The second important fact is that accept( ) creates and returns an instance of Socket. The socket that accept( ) returns is created inside the body of the accept( ) method for a single client; it encapsulates a connection between the client and the server.

Therefore, any server written in Java executes the following sequence of steps:

  1. The server is initialized. Eventually, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required