Simple Client and Server Programs
Dr. David Matuszek,   dave@acm.org,Villanova University

Here are two short Java programs: one that acts as a client, one that acts as a server. The client connects to the server, they exchange a couple of messages and quit.

Both Client and Server have to import two essential packages:

import java.net.*;
import java.io.*;

Every computer has an IP address. The IP address may be permanently assigned (a static IP address), or it may be dynamically assigned (and possibly different every time the computer is restarted). The IP address is like a phone number; the Client program has to know the IP address of the computer it is trying to connect to (but the Server program doesn't need to know the IP address of the computer that is running the Client program). To find the IP address for a computer, open an MS-DOS window and enter the command ipconfig. The IP address consists of four numbers separated by periods, for example, 153.104.202.116 .

The IP address gets you to the computer, but there might be many servers running on the computer. Our Server needs to use a port number, which is like a telephone extension. You can use any number you like between 1024 and 9999 for a port number; the only requirement is that some other server isn't already using it. If some other server is using it, you will get an error message that says so, and you can just pick another number. (Numbers below 1024 are reserved for use by things like FTP and HTTP servers). Your program could even use several different ports.

In the following code, I'm using my office phone number as a port number.

    int PORT = 5654;  // Any number between 1024 and 9999 will do

Since there are a lot of things that can go wrong, you need Exception handlers all over the place. For simplicity, I'm going to ignore all the Exceptions, but they are in the actual sample code.

On the Server:

  1. Create a ServerSocket. This is used to accept calls from clients.
    ServerSocket ss;
    ss = new ServerSocket(PORT);
  2. Wait for a client to connect. This code "blocks"--that is, the program doesn't go any further until a client connects, it just waits right here. When a client connects, accept() returns a Socket for us to use.
    Socket client;
    client = ss.accept();
  3. Define an input stream, so that we can read from this client. In this example, our input stream is provides text (Strings).
    BufferedReader input;
    input = new BufferedReader(
              new InputStreamReader(client.getInputStream()));
  4. Define an output stream, so that we can write to this client. In this example, our output stream is one that accepts text (Strings).
    PrintStream output;
    output = new PrintStream(client.getOutputStream());
  5. Read something. This code blocks waiting for input, so the client had better send us something.
    String message = input.readLine();
  6. Write something.
    output.println("Hello, Client!");
  7. Quit. It is essential to close all the sockets; if you don't, the next time you try to run the Server, the operating system may think those sockets are still in use, and not let you have them.
    input.close();
    output.close();
    client.close();

On the Client:

  1. You have to know the IP address of the computer and the port number of the server.
    String IP_ADDRESS = "153.104.202.116"; // Like a phone number
    int PORT = 5654;                       // Like an extension
    Note: You can run the client and the server on the same computer. If you do, you can use either the actual IP address of that computer, or the String "localhost".

  2. Place a call to the server. This code "blocks"--that is, the program doesn't go any further until the server responds, it just waits right here. When the server responds, we have a Socket we can use.
    server = new Socket(IP_ADDRESS, PORT);
  3. Define an input stream, so that we can read from this client. In this example, our input stream is provides text (Strings).
    BufferedReader input;
    input = new BufferedReader(
              new InputStreamReader(server.getInputStream()));
  4. Define an output stream, so that we can write to this client. In this example, our output stream is one that accepts text (Strings).
    PrintStream output;
    output = new PrintStream(server.getOutputStream());
  5. Write something.
    output.println("Hello, Server!");
  6. Read something. This code blocks waiting for input, so the server had better send us something.
    String response = input.readLine();
  7. Quit.

To run these programs:

  1. Open an MS-DOS window and run the server by typing java Server. This step must be done first.
  2. Open a second MS-DOS window and run the client by typing java Client.

How to prevent blocking:

In the above (simple) example, the server blocks until the client writes something, then the client block until the server writes something. This is clearly unacceptable in a "real" program.

The solution is simple: Create another Thread to do the reading. This other thread will block waiting for input while the rest of the program continues. When it gets input, it puts the input someplace that the rest of the program will find it, then waits for the next input.

Source code (right-click to download):

Server.java
Client.java