001package edu.pdx.cs410J.net;
002
003import java.io.*;
004import java.net.*;
005import java.util.Date;
006
007/**
008 * A server that waits for a {@link DateClient} to connect to it.
009 * When a client connects, it waits for 5 seconds before returning the
010 * current date and time.  This program demonstrates the ports that
011 * are actually used when a socket connection is made.  The server
012 * will exit after five clients have connected to it.
013 *
014 * @author David Whitlock
015 * @since Fall 2005
016 */
017public class DateServer {
018
019  private static final PrintStream out = System.out;
020  private static final PrintStream err = System.err;
021
022  /**
023   * Listens for 5 clients to attach.  The client's request is
024   * handled in its own {@link DateServer.Worker} thread.
025   */
026  public static void main(String[] args) {
027    int port = Integer.parseInt(args[0]);
028
029    try {
030      ServerSocket server = new ServerSocket(port, 5);
031      for (int i = 0; i < 5; i++) {
032        out.println("Server listening on " + server.getInetAddress() + 
033                    ":" + server.getLocalPort());
034        Socket socket = server.accept();
035        out.println("Server accepted client " + i);
036
037        // Fire off a thread to write the date
038        Worker worker = new Worker(socket);
039        worker.start();
040      }
041      
042      out.println("Server exiting");
043
044    } catch (IOException ex) {
045      err.println("** IOException: " + ex);
046      System.exit(1);
047    }
048  }
049
050  /**
051   * A worker thread that waits five seconds before returning the
052   * current date.
053   */
054  static class Worker extends Thread {
055    private final Socket socket;
056
057
058    Worker(Socket socket) {
059      this.socket = socket;
060    }
061
062    public void run() {
063      try {
064        out.println("Server running on " + socket.getLocalAddress() +
065                    ":" + socket.getLocalPort());
066        out.println("Server communicating with " + socket.getInetAddress() 
067                    + ":" + socket.getPort());
068
069        Thread.sleep(5 * 1000);
070
071        OutputStream os = socket.getOutputStream();
072        PrintWriter pw = new PrintWriter(os, true);
073        Date now = new Date();
074        pw.println(now.toString());
075        pw.flush();
076        pw.close();
077
078      } catch (InterruptedException ex) {
079        err.println("** InterruptedException: " + ex);
080        System.exit(1);
081
082      } catch (IOException ex) {
083        err.println("** IOException: " + ex);
084        System.exit(1);
085      }
086    }
087  }
088
089}