import java.net.*;
import java.io.*;

public class Server {

  public static void main(String args[]) {
    ServerSocket ss = null;  // Switchboard used to make connection
    Socket client = null;    // After connection, use this for I/O
    int PORT = 5654;  // Any number between 1024 and 9999 will do
    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 {
      // Wait for a client to connect (send us a socket)
      client = ss.accept();
      System.out.println("Just accepted a call from a client.");
      // Associate reader and writer streams with that client.
      // You could have an array of Sockets, one per client.
      input = new BufferedReader(
                    new InputStreamReader(client.getInputStream()));
      output = new PrintStream(client.getOutputStream());
      // Read, then write. Without another thread, order is critical.
      String message = input.readLine(); // sait for input
      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 { // The sockets MUST be closed.
      try {
        input.close();
        output.close();
        client.close();
      }
      catch (Exception e) { // closing could cause an Exception
        e.printStackTrace();
        System.exit(0);
      }
    }
  }
}
