import java.lang.Thread;
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;

public class Server_Threaded extends Frame  {

//*****  Single-thread server, accepts multiple messages
//            expected to be run on capefear.cs.unc.edu:8888

MyFrame outerBox;

TextField hostDisplay, portDisplay;
TextArea logDisplay, msgDisplay;
Panel topPanel;
Panel middlePanel;
Panel buttonPanel;
Button listenButton, quitButton;

public static final String DEFAULT_HOST = "gamma.cs.unc.edu";
public static final int DEFAULT_PORT = 8888;
String host;

// **************

  public Server_Threaded ()  {
    super ( "Server_Threaded " );
  }  // end Server_Threaded constructor

// **************

  public static void main ( String [ ] args )  {
    Server_Threaded server = new Server_Threaded ();
    server.buildUI ();
  }  // end main

// **************

  public boolean action (Event event, Object arg) {

    if (event.target == listenButton )  {
       this.connectClient ();
      return true;
    }  // end listenButton 

    if (event.target == quitButton )  {
      hide ();
      dispose ();
      System.exit ( 0 );
      return true;
    }  // end quitButton 

    return false;  // action not handled here

  }  // end action

// **************

  public boolean handleEvent ( Event event )  {

    if ( event.id == Event.WINDOW_ICONIFY )  {
      hide ();
      dispose ();
      System.exit ( 0 );
    }  // end if

    return super.handleEvent ( event );

  }  // end handleEvent 

// **************

  public void connectClient ( )  {

  ServerSocket listenSocket;
  Socket connection;
  OutputStream output;
  InputStream input;
  String host;
  int port;
  boolean again = true;
  String stringIn, stringOut;
  int mark;

    if ( ! ( portDisplay.getText () ).equals ( "" ) ) port = Integer.parseInt ( portDisplay.getText () );
    else port = DEFAULT_PORT;

    try  {
      logDisplay.setText ( "Server started:  listening on port " + port + "\n" );
      listenSocket = new ServerSocket ( port );
      connection=  listenSocket.accept ();
      input = connection.getInputStream ();
      output = connection.getOutputStream ();
      logDisplay.appendText ( "Connection request received\n" );

      while ( again )  {

        stringIn = getMsg ( input );
System.out.println ( "Server stringIn = " + stringIn);
        if ( stringIn != "$$" ) {  // valid message
          msgDisplay.setText ( stringIn);
          logDisplay.appendText ( "Message, below, received\n" );
        }  // end if
        else  {  // end of session
          again = false;
System.out.println ( "EOF" );
System.out.println ( "Server again = " + again );
          return;
        }  // end if

        if ( again )  {  // session still active
          putMsg ( output, msgDisplay.getText () );
          logDisplay.appendText ( "Message, below, sent to client \n" );
          logDisplay.appendText ( "Message length = " + ( msgDisplay.getText () ).length () + "\n" );
        }  // end if
        else  {  // session ended
          logDisplay.appendText ( "Closing socket\n" );
           try {
            connection.close ();
System.out.println ( "socket closed" );    
           }  // end try
             catch ( IOException except)  {
             except.printStackTrace ();
           }  // end catch
         }  // end else

      }  // end while ( again )

    }  catch ( IOException except )  {
          except.printStackTrace ();
    }  // end catch

  }  // end connectClient 

// **************

  public String getMsg ( InputStream input )  {
    char[] charArray = new char [ 1024 ];
  char c;
        try {
           int i = 0;
            while ( ( (c = (char) input.read () ) != '#' ) && (i < 1024) ) {
             charArray [ i ] =  c ;
             i++;
           }  // end while
        }  catch ( IOException except )  {
          except.printStackTrace ();
        }  // end catch
         String string = new String ( String.valueOf ( charArray) );
System.out.println ( "Server:getMsg string = " + string);

          return string;
  }  // end getMsg

  public void putMsg ( OutputStream output, String string )  {
    try {
      for ( int i = 0; i < string.length(); i++ ) {
        output.write ( (int) string.charAt ( i ) );
      }  // end for
      output.write ( (int)'#' );  // end of message mark
    }  catch ( IOException except )  {
          except.printStackTrace ();
    }  // end catch
  }  // end putMsg

// **************

  public void buildUI ()  {

  try {
    InetAddress here = InetAddress.getLocalHost ();
    host = here.toString();
  }
  catch (UnknownHostException e) { ;}
  hostDisplay = new TextField ( host, 30 );
  portDisplay = new TextField ( Integer.toString ( DEFAULT_PORT ), 4 );
  topPanel = new Panel ();
  topPanel.setLayout ( new BorderLayout () );
  topPanel.add ( "North", hostDisplay );
  topPanel.add ( "South", portDisplay );

  logDisplay = new TextArea ( 40, 10 );
  msgDisplay = new TextArea ( 40, 10 );
  middlePanel = new Panel ();
  middlePanel.setLayout ( new GridLayout ( 2, 1 ) );
  middlePanel.add ( logDisplay );
  middlePanel.add ( msgDisplay );

  listenButton = new Button ( "Listen" );
  quitButton = new Button ( "Quit" );
  buttonPanel = new Panel ( );
  buttonPanel.add ( listenButton );
  buttonPanel.add ( quitButton );

  outerBox = new MyFrame ( this, "Server_Threaded" );
  outerBox.add ( "North", topPanel );
  outerBox.add ( "Center", middlePanel );
  outerBox.add ( "South", buttonPanel );

  outerBox.resize ( 350, 400 );
  outerBox.show ();

  }  // end buildUI 

}  // end Server_Second 




// ********************  MyFrame Class *******************

class MyFrame extends Frame  {
  Frame source;

  MyFrame ( Frame a )  {
    super ( );
    source = a;
  }  // end constructor

  MyFrame ( Frame a, String title )  {
    super ( title );
    source = a;
  }  // end constructor

  public boolean action ( Event event, Object object )  {
    if ( source.action ( event, object ) ) return true;
    else return false;
  }  // end action

  public boolean handleEvent ( Event event )  {
    if ( source.handleEvent ( event ) ) return true;
    else return super.handleEvent ( event );
  }  // end handleEvent

}  // end MyFrame

