
import java.io.*;
import java.net.*;
import sun.net.NetworkServer;

/**
 * A program that echoes to standard output an HTTP
 * request, whether GET or POST.
 *
 * Usage: java DiagServer [port]
 *
 * If you spawn the server on a port already in use, you will be informed
 * "Server failed to start: java.net.BindException: Permission denied".
 * Note that the server's default choice of ports is 80.
 *
 * Excerpted from
 * http://hotwired.lycos.com/webmonkey/99/36/index3a_page4.html?tw=backend.
 */

public class DiagServer extends NetworkServer {

  public static void main(String[] args) {
    int port = 80;
    try {
      port = Integer.parseInt(args[0]);
    }
    catch (Exception e) {
      //You might want to catch a NumberFormatException here,
      //or do some more sophisticated command line parsing.
    }
    try {
      DiagServer ds = new DiagServer();
      ds.startServer(port);
      System.err.println("DiagServer started on port " + port);
      System.err.println("");
    }
    catch (IOException ioe) {
      System.err.println("Server failed to start: " + ioe);
    }
  } //main

  public void serviceRequest() throws IOException {
    int byteCount = 0;
    while (clientIsOpen() && (byteCount <1000)) {
      byte b = (byte) clientInput.read();
      byteCount++;
      System.out.write(b);
      System.out.flush();
    }
  } //serviceRequest
}
