// (C) Copyright Jack Culpepper 1997
// This code may not be distributed without permission.
package gestalt;

import java.net.*;
import java.io.*;
import java.util.*;
import gestalt.Connection;

public abstract class Client extends Thread {
  protected String hostname;

  // exit with an error message when an exception occurs
  public static void fail( String msg ) {
    report( msg );
    System.exit( 1 );
  }

  public static void report( String str ) {
    System.out.println( "Client: " + str );
  }

  public Client( String hostname ) {
    this.hostname = hostname;
    this.start();
  }

  public Client( String hostname, String threadname ) {
    // name thread
    super( threadname );

    this.hostname = hostname;
    this.start();
  }

  public abstract void begin( Connection c );

  public void run() {
    // create a socket to the server
    try {
      Socket s = new Socket( hostname, Constants.clientPort );

      // make a connection out of the socket
      try {
        report( "Creating a new connection." );
        Connection c = new Connection( s, getThreadGroup() );

        // we're off!
        begin( c );
        c.stop();
        c.close();
      }
      catch ( IOException e ) {
        report( "IOException creating Connection: " + e );
      }
    }
    catch ( UnknownHostException e ) {
      report( "Exception: " + e );
    }
    catch ( IOException e2 ) {
      report( "Exception: " + e2 );
    }
  }
}
