The Java Program: Server.java

  1 // Server.java -- Echo server
  2 
  3 import Connection;
  4 import java.net.Socket;
  5 import java.net.ServerSocket;
  6 import java.io.IOException;
  7 
  8 
  9 public class Server extends Thread {
 10    public final static int DEFAULT_PORT = 56789;
 11    private int port;
 12    private ServerSocket listen_socket;
 13     
 14    // Create a ServerSocket to listen for connections on; start the thread.
 15    public Server (int port) {
 16       if (port == 0) port = DEFAULT_PORT;
 17       this.port = port;
 18       try {
 19          listen_socket = new ServerSocket(port);
 20          System.out.println ("Server: listening on port " + port);
 21          this.start();
 22       } catch (IOException e) {
 23          e.printStackTrace (System.err);
 24       }
 25    }
 26     
 27    // The body of the server thread.  Loop forever, listening for and
 28    // accepting connections from clients.  For each connection, create
 29    // a Connection object to handle communication through the new Socket.
 30    public void run() {
 31       try {
 32          while (true) {
 33             Socket client_socket = listen_socket.accept();
 34             Connection c = new Connection (client_socket);
 35          }
 36       } catch (IOException e) {
 37          e.printStackTrace (System.err);
 38       }
 39    }
 40     
 41    // Start the server up, listening on an optionally specified port
 42    public static void main (String[] args) {
 43       int port = 0;
 44       if (args.length == 1) {
 45          try {
 46             port = Integer.parseInt(args[0]);
 47          } catch (NumberFormatException e) {
 48             port = 0;
 49          }
 50       }
 51       new Server(port);
 52    }
 53 }