import java.io.*;
import java.net.*;

/* This is a serial bidirectional network server.
   It takes one command line parameter, the port number to listen on.
   All input coming from standard input (System.in) goes to the network.
   All input coming from the network goes to standard output (System.out).

   This implementation has the following unusual behavior:
   When the client terminates the connection, a new connection will not be
   accepted until 2 attempts are made to send input to the client.
 */

public class SerialNetworkServer {

   int port;
   ServerSocket serverSocket;
   boolean success = false;

   public SerialNetworkServer(int port) {
      this.port = port;
      try {
         serverSocket = new ServerSocket(port);
         success = true;
      } catch (IOException e) {}
   }

   public boolean getSuccess() {
      return success;
   }

   public void listen() {
      Socket sock;
      DataInputStream in;
      DataOutputStream out;
      DataInputStream standardIn;
      DataOutputStream standardOut;
      Copy2Files copy2Files;
      standardOut = new DataOutputStream(System.out);
      standardIn = new DataInputStream(System.in);
      while (true) {
         try {
            System.out.println(
                    "The server is waiting for a connection on port " +
                    port);
            sock = serverSocket.accept();
            System.out.println("A connection has been made from " +
                               sock.getRemoteSocketAddress());

            in = new DataInputStream(sock.getInputStream());
            out = new DataOutputStream(sock.getOutputStream());
            copy2Files = new Copy2Files(in, standardOut, standardIn, out);
            copy2Files.copyAll();
            System.out.println("Bytes transferred: " + copy2Files.getCount1() +
                               " and " + copy2Files.getCount2());
            try {
               sock.close();
            } catch (IOException e) {}
         } catch (IOException e) {}
      }
   }

   public static void main(String[] args) {
      int port;
      SerialNetworkServer server;
      if (args.length != 1) {
         System.out.println("Usage: java SerialNetworkServer port");
         System.exit(1);
      }
      port = Integer.parseInt(args[0]);
      System.out.println("Using port number " + port);
      server = new SerialNetworkServer(port);
      server.listen();
   }

}
