A simple client and server in Java

In our networking introduction, we introduced the basic notions of:

In this section, we look at how to program a simple client-server application in Java. The idea is:

To get us started, we'll consider the case where only one client can connect at once. On a real-life production server receiving a moderate volume of connections and/or where each connection took any significant time to be serviced, we would need to allow multiple clients to connect simultaneously, and in subsequent section we will consider how to adapt our program to cope with mutliple clients.

On the server

Our example server is going to perform calculations on behalf of the client. The idea is that a client connects, sends it a number and operation type, and the server sends back the result. In this section, we'll look at the basic server-side Java code, then in the next section we'll look at the client code.

Creating the server socket

To start off with, our calculation server will sit continually listening for connections. When an incoming connection is received from a client, the server will have a "conversation" with the client that we'll look at in a moment.

To accept incoming connections, the server-side code needs to open a server socket. In our analogy of offices with telephones, we are creating an operator that sits waiting for calls on a particular "extension". In networking terms, we create a server socket listening for connections to a particular port number. To do so, we create a ServerSocket object and continually call its accept() method:

public void runServer() throws IOException {
  ServerSocket ss = new ServerSocket(80);
  try {
    while (!shutdownRequested) {
      Socket s = ss.accept();
      try {
      } finally {
  } finally {

In this example, we've chosen port number 80, which is the standard port number for a web server (although our server isn't actually a web server, so long as we're not running a web server on the same machine, it essentially doesn't matter).

When we call accept(), the program— or in fact, the current thread— will wait for a connection. When a connection is made, the accept() method "wakes up" and returns us a Socket object. Via this Socket object, we can read the data sent to us by the client and send data back. In a moment, we'll write the processConnection() method to do so. Note that we're in a single loop in a single thread: so for the moment while we're processing one connection, we can't be accepting another. Two issues that we'll have to deal with later on are therefore:

For now, we'll put these issues on the back burner and look at the processConnection() method.

Next: the "conversation" with the client

On the next page, we look at handling the server-side connection, which includes reading and writing data to the Socket object returned to us via the accept() method.

[an error occurred while processing this directive]