import java.io.*;
import java.net.*;

public class EchoServer {
  public static void main(String[] args) throws IOException {

    ServerSocket echoSocket = null;
    Socket clientSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;

    try {
      //Make the server socket.  This is ONLY used for accepting incoming
      //connection requests, not for other communication
      echoSocket = new ServerSocket(7777);

      //Wait for a client to connect.  Upon connection, get the new socket
      //to use for communication with the client
      clientSocket = echoSocket.accept();

      //Get and output stream for writing from the client socket
      out = new PrintWriter(clientSocket.getOutputStream(), true);
      //Get an input stream for reading from the client socket
      in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    }
    catch (UnknownHostException e) {
      System.err.println("Don't know about host: localhost.");
      System.exit(1);
    }
    catch (IOException e) {
      System.err.println("Couldn't get I/O for the connection to: localhost.");
      System.exit(1);
    }

    //Use a try block to catch SocketExceptions, in case the client
    //disconnects prematurely
    try {
      //Read in each line from the client and echo it back by writing it to
      //the client through the clientSocket
      String userInput;
      while ( (userInput = in.readLine()) != null) {
        System.out.println("Got from client: " + userInput);
        //Echo back to client
        out.println(userInput);
      }
    }
    catch (SocketException e) {}

    out.close();
    in.close();
    clientSocket.close();
    echoSocket.close();
  }
}
