FileDocCategorySizeDatePackage
ChatApplet.javaAPI DocExample5527Mon Oct 16 19:44:06 BST 2000None

ChatApplet.java

// File: ChatApplet.java
// T Balls : Nov 1999
// Applet client to chat system

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class ChatApplet extends Applet implements ActionListener
{  public void init()                                           /**/
   {  setLayout( new BorderLayout() );
      client= new Chatter( getDocumentBase().getHost() );
      add( client, BorderLayout.CENTER );
   }

   private Chatter client;
   private TextField alias = new TextField();

   public void start()                                          /**/
   {  add( alias, BorderLayout.SOUTH );
      alias.addActionListener( this );
      client.init();
   }

   /**
      A one-shot event handler.

      Sole purpose is to get an alias from the user and get the client connected
      The TextField is blanked by removing it from the applet
      The action events are also cancelled
      The client has a controlling thread started if the connection is successful
   */
   public void actionPerformed( ActionEvent e )
   {  remove(alias);
      if( client.connect( alias.getText() ) )
      {  alias.removeActionListener( this );
         new Thread( client ).start();
      }
   }
   
   public void stop()
   {  client.disconnect();
   }

}

/**
   Handle Client side of connection.
   
   Has a large scrollable text area for incoming text and a single line
   for outgoing messages.  The incoming messages are handled by a separate
   thread of control.  Output happens in response to a return key being
   pressed in the data entry field.
   Top line shows current connection status
   
   Failure of the socket stream causes an error message to be displayed
   and disconnects the client
*/
class Chatter extends Panel implements Runnable, ActionListener 
{  /**
      Create screen representation of chat client
   */
   public Chatter( String aHost )
   {  setLayout( new BorderLayout() );
      host = aHost;
      title = new Label( "Chat Client : not connected" );
      add( title, BorderLayout.NORTH );
      text = new TextArea( "", 15, 40 );
      add( text, BorderLayout.CENTER );
      send = new TextField( "Type an alias on the next line:" );
      send.addActionListener( this );
      add( send, BorderLayout.SOUTH );
   }

   public void init()                                       /**/
   {  title.setText( "Chat Client : not connected" );
      send.setText( "Type an alias on the next line:" );
   }

   private String host;
   private String alias;
   private int port = 34567;
   private Label title;
   private TextArea text;
   private TextField send;
   BufferedReader in = null;
   BufferedWriter out = null;
   Socket s = null;
   private boolean running = false;
   
   /**
      Attempt to establish a connection with Server.
      
      @see Server
   */
   public boolean connect( String anAlias )
   {  alias = anAlias;
      // attempt to connect to server
      try
      {  s =new Socket( host, port );
      }
      catch( UnknownHostException e )
      {  text.append( "\n*** Host not known" );
         return false;
      }
      catch( IOException e )
      {  text.append( "\n*** Can't connect to " + host );
         return false;
      }
      // connection OK so get I/O streams
      try
      {  in = new BufferedReader( 
                 new InputStreamReader( 
                    s.getInputStream() ) );
         out = new BufferedWriter( 
                 new OutputStreamWriter( 
                    s.getOutputStream() ) );
      }
      catch( IOException e )
      {  text.append( "\n*** Failed to create valid link to " + host );
         return false;
      }
      
      // now send name to server
      try
      {  out.write( alias, 0, alias.length() );
         out.newLine();
         out.flush();
      }
      catch( IOException e )
      {  text.append( "\n*** Failed to send name to server" );
         return false;
      }
      
      title.setText( "Chat to host: " + host +
                " on port: " + port +
                " as " + alias );
      send.setText( "Type your messages here" );
      running = true;
      return true; 
   }
     
   /**
      When enter is pressed in text field, send string to server
   */
   public void actionPerformed( ActionEvent e )
   {  String msg = send.getText();
      send.setText( "" );
      try
      {  out.write( msg, 0, msg.length() );
         out.newLine();
         out.flush();
      }
      catch( IOException ioe )
      {  text.append( "\n*** Can't send message - connection might have been lost." );
      }
   }

   /**
      Capture strings from socket and append to text area
   */
   public void run()
   {  // place data from socket stream on to screen
      String line = "";
      try
      {  while( running )
         {  line = in.readLine(); 
            if( line == null )
            {  throw new IOException();
            }
            text.append( line + "\n" );
         }
      }
      catch( IOException e )
      {  text.append( "\n\n*** Connection to server lost\n" );
      }   
   }

   /**
      Kill the connection and terminate the thread
   */
   public void disconnect()
   {  running = false;
      try
      {  s.close();   
      }
      catch( IOException e )
      {  e.printStackTrace();
      }
   } 
}