001package edu.pdx.cs410J.net;
002
003import java.io.*;
004import java.net.*;
005
006/**
007 * This program listens to a socket.  It expects strings from a
008 * <code>Speaker</code>.  The conversation terminates with the word
009 * "bye".
010 */
011public class Listener {
012  private static PrintStream out = System.out;
013  private static PrintStream err = System.err;
014
015  /**
016   * Main program that reads the port number to listen to from the
017   * command line.
018   */
019  public static void main(String[] args) {
020    int port = 0;
021
022    try {
023      port = Integer.parseInt(args[0]);
024    } catch (NumberFormatException ex) {
025      err.println("** Bad port number: " + args[0]);
026      System.exit(1);
027    }
028
029    try {
030      // Backlog of 5 messages
031      ServerSocket server = new ServerSocket(port, 5);
032
033      // Wait for the Speaker to connect
034      Socket socket = server.accept();
035
036      // Read from the Socket
037      InputStreamReader isr = 
038        new InputStreamReader(socket.getInputStream());
039      BufferedReader listener = new BufferedReader(isr);
040
041      String line = "";
042      while (!line.equals("bye")) {
043        line = listener.readLine();
044        out.println(line);
045      }
046
047      listener.close();
048
049    } catch (IOException ex) {
050      err.println("** IOException: " + ex);
051      System.exit(1);
052    }
053  }
054}