/*
 * Java Network Programming, Second Edition
 * Merlin Hughes, Michael Shoffner, Derek Hamner
 * Manning Publications Company; ISBN 188477749X
 *
 * http://nitric.com/jnp/
 *
 * Copyright (c) 1997-1999 Merlin Hughes, Michael Shoffner, Derek Hamner;
 * all rights reserved; see license.txt for details.
 */

import java.io.*;
import java.net.*;

public class STServer {
  public static void main (String[] args) throws IOException {
    if (args.length != 1)
      throw new IllegalArgumentException ("Syntax: STServer <port>");
    Socket client = accept (Integer.parseInt (args[0]));
    try {
      InputStream in = client.getInputStream ();
      OutputStream out = client.getOutputStream ();
      out.write ("You are now connected to the Echo Server.\r\n"
                 .getBytes ("latin1"));
      int x;
      while ((x = in.read ()) > -1)
        out.write (x);
    } finally {
      System.out.println ("Closing");
      client.close ();
    }
  }
  
  static Socket accept (int port) throws IOException {
    System.out.println ("Starting on port " + port);
    ServerSocket server = new ServerSocket (port);
    System.out.println ("Waiting");
    Socket client = server.accept ();
    System.out.println ("Accepted from " + client.getInetAddress ());
    server.close ();
    return client;
  }
}
