This applet supports two-way chatting between users. It implements a client for the ConnectionBroker server, which can set up a relayed connection between a pair of such clients. There are really two functions: The user can register with the server as a client who is willing to accept a connection, or the user can make a connection with one of the clients who is waiting on the server. The applet retrieves and displays a list of waiting clients when it starts. There is a Refresh button that the user can click to refresh this list (since the list of waiting clients can change from time to time).

The user connects with one of the clients on the list by clicking it and then clicking a Connect button. Finally, there is a register button that will add the user to the list and then wait for a connection. There is an input box where the user can enter a name or other information to be displayed in other users’ client lists. The use can be a party to multiple connections simultaneously. A separater window opens for each connection that can be used to send and retrieve messages. (Note that there is nothing to stop a user from chatting with him or herself.)

An applet parameter named “server” can be used to specify the name or IP number of the server computer. If none is specified, the computer from which the applet was loaded is used. Another applet parameter, named “port”, can be used to specify the port on which the server is listening. If none is specified, then the port given by the constant DEFAULT_PORT is used. This class can also be run as a standalone application. In that case, the server must be specified as the first command-line parameter. The port, if differnent from the DEFAULT_PORT, can be specified as the second parameter.

*     MYCPLUS Sample Code -     *
*                                                     *
*   This code is made available as a service to our   *
*      visitors and is provided strictly for the      *
*               purpose of illustration.              *
*                                                     *
* Please direct all inquiries to saqib at *

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;

public class BrokeredChat extends JApplet implements ActionListener {

   public static void main(String[] args) {
        // Run as a standalone program in its own window,
        // using information about the server from the command line.
      if (args.length == 0) {
         System.out.println("Usage:  java BrokeredChat  []");
      BrokeredChat applet = new BrokeredChat(); = args[0];   // Set these values so the applet
      applet.port = DEFAULT_PORT;  //    won't do it when it starts.
      if (args.length > 1) {
         try {
            applet.port = Integer.parseInt(args[1]);
         catch (NumberFormatException e) {
      JFrame window = new JFrame("BrokeredChat");
          // This is a nasty fudge.  The applet is not
          // really used as an applet.  It does serve as
          // action listener for the buttons.

   /* Command chars that are used for communicating with the
      server.  See for more info. */

   static final char REGISTER = '[';          // Commands that the
   static final char CONNECT = '=';           //    applet can send
   static final char SEND_CLIENT_LIST = ':';  //    to the server.

   static final char NOT_AVAILABLE = '!';     // Responses from the
   static final char CONNECTED = '.';         //    server.
   static final char CLIENT_INFO = '>';
   static final char END_CLIENT_INFO = '<';

   static final int DEFAULT_PORT = 3030;  // Listening port on server,
                                          //   if another is not given.

   JLabel display;         // Displays infomation to the user.
   JComboBox clients;      // List of available clients from the server.
   JButton connectButton;  // For connecting to one of the waiting clients.
   JButton refreshButton;  // For refreshing the list of clients.
   JButton registerButton; // For registering with the server.
   JTextField infoInput;   // Contains info sent to server to appear
                           //   as a description of this client, when
                           //   the client registers with the server.

   ArrayList clientStrings;  // Client descriptions received from
                             //   server.  Each description is a
                             //   ID number, followed by a space, followed
                             //   by the client's info.

   String computer;  // Computer where server runs.
   int port;         // Port on which server listens.

   public void init() {

   JPanel makeInterfacePanel() {
         // Create a panel containing the user interface.
         // This is used as the content pane of the applet
         // (or of the frame if this class is run as an application).

      JPanel panel = new JPanel();

      panel.setLayout(new GridLayout(4,1,5,5));
      JPanel top = new JPanel();
      top.setLayout(new BorderLayout(2,2));
      JPanel middle = new JPanel();
      middle.setLayout(new BorderLayout(5,5));
      JPanel bottom = new JPanel();
      bottom.setLayout(new GridLayout(1,2,5,5));

      display = new JLabel("",JLabel.CENTER);
      display.setForeground(new Color(200,0,0));


      clients = new JComboBox();

      connectButton = new JButton("Connnect to Selected User");

      refreshButton = new JButton("Refresh User List");

      registerButton = new JButton("Register");

      infoInput = new JTextField();

      top.add(new JLabel("Register with Server as: "), BorderLayout.WEST);
      middle.add(new JLabel("List of Available Users: "), BorderLayout.WEST);

      if (computer == null) {
           // Computer will be non-null if this is being run
           // as a stand-along application, not an applet.
         String portStr = getParameter("port");
         if (portStr == null)
            port = DEFAULT_PORT;
         else {
            try {
               port = Integer.parseInt(portStr);
            catch (NumberFormatException e) {
               port = DEFAULT_PORT;
         computer = getParameter("server");
         if (computer == null) {
               // Use the computer from which the applet was loaded.
            computer = getCodeBase().getHost();

      return panel;

   }  // end makeInterfacePanel();

   public void actionPerformed(ActionEvent evt) {
         // Respond when the user clicks one of the buttons.
      Object source = evt.getSource();
      if (source == connectButton) {
      else if (source == registerButton || source == infoInput) {
      else {

   void doCommand(char command) {
         // Create a thread to contact the server to carry out
         // the command, which can be one of CONNECT, REGISTER,
         // or SEND_CLIENT_LIST.
      String message;  // Command to be sent to server.
      String name;     // Name for connection window.
      if (command == CONNECT) {
            // Connect to the user select in the client list.
            // The command to the server must contain the ID
            // number of the client.  This is in the clientStrings
            // list.  The String in this list consists of the
            // client ID followed optionally by a space and the
            // description under which that client registered.
         int partner = clients.getSelectedIndex();
         if (clientStrings == null || partner < 0 ||
                                partner >= clientStrings.size()) {
              // This really shouldn't be possible.
            display.setText("Can't connect -- no user!");
         String info = (String)clientStrings.get(partner);
         int pos = info.indexOf(" ");
         if (pos > 0) {
            message = "" + CONNECT + info.substring(0,pos);
            name = info.substring(pos+1);
         else {
            message = "" + CONNECT + info;
            name = "unknown user";
      else if (command == REGISTER) {
            // Register with the server.  The string from the
            // infoInput is sent to the server as the description
            // of the client and will appear in a client list
            // that is downloaded from the server.
         name = infoInput.getText().trim();
         if (name.length() == 0) {
            display.setText("To register, you must enter a name.");
         message = REGISTER + name;
         display.setText("Contacting server to register you...");
      else {
            // The command is to get the client list from the server.
         message = "" + SEND_CLIENT_LIST;
         display.setText("Contacting server to get user list...");
         name = null;
      registerButton.setEnabled(false);  // Buttons are disabled until operation completes.
      new ConnectionHandler(message,name);  // Create thread to do the command.

   class ConnectionHandler extends Thread {
         // A thread to handle a connection to the server.
      String message;  // Message to be sent to the server.
                       // First character tells which of the three
                       // possible types of message this is.
      String name;  // Name to appear in the title bar of the ChatWindow.
                    // Used only for CONNECT and REGISTER commands.
      ConnectionHandler(String message, String name) {
         this.message = message; = name;
         start();  // Thread starts as soon as it is created.
      public void run() {
         Socket connection = null;
         ArrayList clients = null;  // Will be the list of clients from the server.
         String displayText = "Client list has been received.";
                  // This will be changed if an error occurs or if the
                  // CONNECT or REGISTER commands complete.
         try {
            if (message.charAt(0) == REGISTER) {
                   // Register with the server and open a server window
                   // to wait for a connection request to come in from
                   // another user.
               connection = new Socket(computer,port);
               PrintWriter out = new PrintWriter(connection.getOutputStream());
               if (out.checkError())
                  throw new IOException("Can't send command.");
               new ChatWindow("Outgoing Connection (" + name + ")",
               displayText = "Opening window to wait for connection";
            else if (message.charAt(0) == CONNECT) {
                   // Try to connect to another user, and open a window
                   // for chatting with that user.
                connection = new Socket(computer,port);
                connection.setSoTimeout(30000);  // only wait 30 seconds
                TextReader in = new TextReader(connection.getInputStream());
                PrintWriter out = new PrintWriter(connection.getOutputStream());
                out.println(message);  // Request the connection.
                if (out.checkError())
                   throw new IOException("Can't send command.");
                String answer = in.getln();  // Read the server's response.
                if (answer.length() == 0 || answer.charAt(0) != CONNECTED) {
                   displayText = "Can't connect to " + name;
                else {
                   connection.setSoTimeout(0);  // Turn off timeout
                   new ChatWindow("Connection to " + name, connection);
                   displayText = "Opening connection to " + name;
               // Get client list.  This is done after a CONNECT or
               // REGISTER, as well as for a SEND_CLIENT_LIST.
            connection = null;
            connection = new Socket(computer,port);
            connection.setSoTimeout(30000);  // Only wait 30 seconds for response.
            TextReader in = new TextReader(connection.getInputStream());
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.println("" + SEND_CLIENT_LIST);  // Request the client list.
            if (out.checkError())
               throw new IOException("Can't send command.");
            ArrayList clientInfo = new ArrayList();
            while (true) {
                  // Get the responses and put them in the clientInfo list.
               String line = in.getln();
               if (line.length() > 0) {
                  if (line.charAt(0) == END_CLIENT_INFO)
                  else if (line.charAt(0) == CLIENT_INFO)
                     clientInfo.add( line.substring(1) );
                     throw new IOException("Bad data received.");
            clients = clientInfo;
         catch (Exception e) {
            displayText = "Error: " + e.getMessage();
            if (connection != null) {
               try {
               catch (IOException e) {

   void finishConnection(final ArrayList clientList, final String displayText) {
         // This is called by the thread that carries out a command, after
         // the command has completed or has caused an error.  If an
         // error occurred, then clientList is null.  Otherwise it is
         // the list of clients, possibly empty, that has been retrieved
         // from the server.  The second parameter is the text to
         // be displayed on the display JLabel.
      SwingUtilities.invokeLater ( new Runnable() {
          public void run() {
             if (clientList == null) {
                clients.addItem("(Can't connect)");
             else if (clientList.size() == 0) {
                clients.addItem("(None available)");
             else {
                  // Show list of clients and turn on connect button
                  // so user can open a connection to one of them.
             refreshButton.setEnabled(true);  // Re-enable buttons.
             clientStrings = clientList;
      } );

   void makeClientList(ArrayList clientInfo) {
         // Change the JComboBox to show the clients in the list.
      clientStrings = clientInfo;
      for (int i = 0; i < clientInfo.size(); i++) {
             // The strings in clientInfo consist of an ID number
             // followed optionally by a user name.  If there is
             // no user name, then the ID number is shown in the list.
         String info = (String)clientInfo.get(i);
         int spacePos = info.indexOf(" ");
         if (spacePos > 0)
            info = info.substring(spacePos+1);

}  // end class BrokeredChat