package com.roguewave.jchat;
import java.net.*;
import java.io.*;
/**
 * The Receptionist class.
 * <P>
 * The Receptionist is a specialized Thread which creates and monitors a ServerSocket
 * for incoming connection requests.  When a Connection is successfully made,
 * it is added to a Dispatcher.
 * </P>
 *
 * @see     java.net.ServerSocket
 * @see     com.roguewave.jchat.Connection
 * @see     com.roguewave.jchat.Dispatcher
 *
 * @version 1.0  96 April 4
 * @author  Eldon J. Metz
 */
public class Receptionist extends Thread {	
  private Dispatcher      dispatcher_ = null;
  private ServerSocket    serverSocket_ = null;
  private Socket          socket_ = null;

  /**
   * Creates a Receptionist.  The Receptionist monitors a ServerSocket on the specified
   * port number.  The specified Dispatcher will be notified when a successful connection
   * is established.
   */
  public Receptionist( int portNumber, Dispatcher aDispatcher) {	
	dispatcher_ = aDispatcher;

   	try {
      serverSocket_ = new ServerSocket( portNumber );
    }
	catch ( IOException ioe ) {
      System.out.println("Receptionist: " + ioe);
    }
  }

  /**
   * The body of the receptionist.  Continually listens for socket connection requests,
   * notifying a Dispatcher when one is successfully established.
   */
  public void run() {
    Connection newConnection = null;

    while( true ) {
      try {
	    socket_ = serverSocket_.accept();
      }
	  catch ( IOException ioe ) {
        System.out.println("Receptionist: " + ioe);
      }
	  newConnection = new Connection(socket_, dispatcher_);
	  newConnection.setServer();
	  dispatcher_.addConnection(newConnection);
    }
  }
}
