Sockets
by David Matuszek

This is example code to go with the Sockets lecture.

The following is the code for a simple Client. It makes the connection, sends a single message ("Hello, Server!"), receives a response, and quits.

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


public class Client1 {
  
  public static void main(String args[]) {
    Socket s;
    BufferedReader input;
    PrintStream output;
    int PORT = 5654;
    
    try {
      s = new Socket("localhost", PORT);  // This is a "client" socket
      input = new BufferedReader(new InputStreamReader(s.getInputStream()));
      output = new PrintStream(s.getOutputStream());
      // Write, then read
      output.println("Hello, Server!");
      String response = input.readLine();
      System.out.println("Client got: " + response);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Here is the corresponding Server code. It does more detailed exception handling than the client, but is otherwise not really much more complicated. This server accepts the connection, reads the message, sends a reply, and quits.

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


public class Server1 {

  public static void main(String args[]) {
    ServerSocket ss = null;
    Socket s = null;
    int PORT = 5654;
    BufferedReader input = null;
    PrintStream output = null;
  
    try {
      // Create the server socket
      ss = new ServerSocket(PORT);
    }
    catch (Exception e) {
      System.out.println("Failed to create ServerSocket.");
      System.exit(0);
    }
    try {
      // Try to connect the server socket
      s = ss.accept();
      System.out.println("Connected to " + PORT + ".");
      input = new BufferedReader(new InputStreamReader(s.getInputStream()));
      output = new PrintStream(s.getOutputStream());
      // Read, then write
      String message = input.readLine();
      System.out.println("Server got: " + message);
      output.println("Hello, Client!");
    }
    catch (Exception e) {
      System.out.println("Failed to connect or do I/O.");
      e.printStackTrace();
    }
    finally {
      try {
        input.close();
        output.close();
        s.close();
      }
      catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
      }
    }
  }
}

To use this code, run the server in one MS-DOS window, then run the client in another. Results:

C:\_Java\Sockets\1>java Server1
Connected to 5654. Server got: Hello, Server!
  
C:\_Java\Sockets\1>java Client1
Client got: Hello, Client!

Here are slightly more complicated versions of the client and server. The differences are:

Here's the client:

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


public class Client2 {
  
  public static void main(String args[]) {
    Socket s;
    BufferedReader input;
    PrintStream output;
    int PORT = 5654;
    
    try {
      s = new Socket("localhost", PORT);  // This is a "client" socket
      input = new BufferedReader(new InputStreamReader(s.getInputStream()));
      output = new PrintStream(s.getOutputStream());
      // Strictly alternate writing and reading
      output.println("Hello, Server!");
      String response = input.readLine();
      System.out.println(response);
      
      output.println("Nothing much to say...");
      response = input.readLine();
      System.out.println(response);
      
      output.println("BYE");
      response = input.readLine();
      System.out.println("Final response: " + response);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

And here's the server:

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


public class Server2 {

  public static void main(String args[]) {
    ServerSocket ss = null;
    Socket s = null;
    int PORT = 5654;
    BufferedReader input = null;
    PrintStream output = null;
  
    try {
      // Create the server socket
      ss = new ServerSocket(PORT);
    }
    catch (Exception e) {
      System.out.println("Failed to create ServerSocket.");
      System.exit(0);
    }
    try {
      // Try to connect the server socket
      s = ss.accept();
      System.out.println("Connected to " + PORT + ".");
      input = new BufferedReader(new InputStreamReader(s.getInputStream()));
      output = new PrintStream(s.getOutputStream());
      // Strictly alternate reading and writing
      String message, reply;
      message = input.readLine();
      System.out.println(message);
      while (!"BYE".equals(message)) {
        reply = "Server got: " + message;
        output.println(reply);
        message = input.readLine();
        System.out.println(message);
      }
    }
    catch (Exception e) {
      System.out.println("Failed to connect or do I/O.");
      e.printStackTrace();
    }
    finally {
      try {
        input.close();
        output.close(); // Sends a null
        s.close();
      }
      catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
      }
    }
  }
}

Run this code as before. Results:

C:\_Java\Sockets\1>java Server2 
C:\_Java\Sockets\1>java Client2 
Connected to 5654.
Hello, Server!
Nothing much to say...
BYE
Server got: Hello, Server!
Server got: Nothing much to say...
Final response: null