Client/Server chat program - wait for connection

From: Ess Eff (esseff_at_coldmail.com)
Date: 10/29/03

  • Next message: Roedy Green: "Re: Client/Server chat program - wait for connection"
    Date: Wed, 29 Oct 2003 08:23:59 +0800
    
    

    Hi,

    I'm trying to modify a client/server chat program that connects
    immediately, to wait till an IP address is selected from a combo box and
    then connect when a connect button is pressed. The combo box is loaded
    from a file of IP addresses and I select the localhost address of
    127.0.0.1.

    I've taken out the app.runClient line from the main class and made it
    the actionPerformed when the connect button is pressed, but the client
    side seems to go dead (won't accept any input) when I do this although
    the connection seems to be working.

    Any help appreciated.

         // Client.java
          // Set up a Client that will read information sent
          // from a Server and display the information.
          import java.io.*;
          import java.net.*;
          import java.awt.*;
          import java.awt.event.*;
          import javax.swing.*;

          public class Client3 extends JFrame
          { private JTextField enter;
             private JTextArea display;
             private JButton connect, send;
             private JComboBox selectIp;
             ObjectOutputStream output;
             ObjectInputStream input;
             String message = "", address = "";

             public Client3()
             {
                super( "Client" );
                Container c = getContentPane();

                JPanel northPanel = new JPanel();
                            northPanel.setLayout( new GridLayout( 2, 1, 3, 3 ) );

    // Enter field and action listener
                enter = new JTextField();
                enter.setEnabled( false );
                enter.addActionListener(
                   new ActionListener() {
                      public void actionPerformed( ActionEvent e )
                      {
                         sendData( e.getActionCommand() );
                      }
                                              }
                                              );
                northPanel.add( enter );

    // Send button
                        send = new JButton("Send >");
                     send.addActionListener(
                new ActionListener()
                {
                        public void actionPerformed( ActionEvent e )
                   {
                      sendBtn( e.getActionCommand() );
                   }
                }
                                                             );
                     northPanel.add( send );
                                                                
                c.add( northPanel, BorderLayout.NORTH );

    // Dislay area
                display = new JTextArea();
                c.add( new JScrollPane( display ),
                       BorderLayout.CENTER );

                JPanel southPanel = new JPanel();
                            southPanel.setLayout( new GridLayout( 1, 2, 3, 3 ) );

    // SelectIP combobox, listener and item listener
                selectIp = new JComboBox();
                selectIp.addItemListener(
                   new ItemListener() {
                      public void itemStateChanged( ItemEvent evt )
                      {
                      if( evt.getSource() == selectIp )
                                      if( evt.getStateChange() == ItemEvent.SELECTED )
                                              address = (String) evt.getItem();
                                     }
                                                                     } );
                                                                        
                southPanel.add( selectIp );

    // Read file and load into combobox
                try
                         {
                         BufferedReader inBuffer = new BufferedReader( new
    FileReader("ipaddress.txt") );
                         String line = inBuffer.readLine();
                          while( line != null )
                            {
                                      selectIp.addItem( line );
                               line = inBuffer.readLine();
                            }
                          inBuffer.close();
                     }
                      catch(IOException e)
                        { System.out.println(e);
                        }

    // Connect button
                connect = new JButton( "Connect");
                connect.addActionListener(
                   new ActionListener() {
                      public void actionPerformed( ActionEvent e )
                      {
                         if( e.getSource() == connect )
                         {
                         runClient();
                                            }
                      }
                                           } );

                southPanel.add( connect );

                c.add( southPanel, BorderLayout.SOUTH );

                setSize( 300, 300 );
                show();
             } // end Client constructor

             public void runClient()
             { Socket client;
                try {
    // Step 1: Create a Socket to make connection.
                   display.setText( "Attempting connection\n" );

                   client = new Socket(
                      InetAddress.getByName( address ), 6000 );
                                    
                            
                   display.setText( "Connected to: "+ address +
                      client.getInetAddress().getHostName() );

    // Step 2: Get the input and output streams.
                   output = new ObjectOutputStream(
                                client.getOutputStream() );
                   output.flush();
                   input = new ObjectInputStream(
                               client.getInputStream() );
                   display.append( "\nGot I/O streams" );

    // Step 3: Process connection.
                   enter.setEnabled( true );

                   do
                   { try {
                         message = (String) input.readObject();
                         display.append( "\n" + message );
                         display.setCaretPosition(
                           display.getText().length() );
                              }
                      catch ( ClassNotFoundException cnfex ) {
                         display.append(
                            "\nUnknown object type received" );
                                                                                                      }
                   } while ( !message.equals( "SERVER>>> quit" ));

    // Step 4: Close connection.
                   display.append( "\nClosing connection.\n" );
                   output.close();
                   input.close();
                   client.close();
                } // end try

                catch ( EOFException eof ) {
                   System.out.println( "Server terminated connection" );
                                                                          }
                catch ( IOException e ) {
                  e.printStackTrace();
                                                                   }

             } // end runClient

    // Action handler for Enter key
             private void sendData( String s )
             {
                try {
                   message = s;
                   output.writeObject( "CLIENT>>> " + s );
                   output.flush();
                   display.append( "\nCLIENT>>>" + s );
                           }
                catch ( IOException cnfex ) {
                   display.append(
                     "\nError writing object" );
                                                                                }
             } // end sendData

    // Action handler for send button
             private void sendBtn( String s )
          {
             try {
                             s = enter.getText();
                                output.writeObject( "SERVER>>> " + s );
                                output.flush();
                                display.append( "\nSERVER>>>" + s );
                     }
             catch ( IOException cnfex ) {
                display.append(
                   "\nError writing object" );
             }
          } // end sendBtn

    // Main
             public static void main( String args[] )
             {
                Client3 app = new Client3();
                app.addWindowListener(
                   new WindowAdapter()
                   {
                      public void windowClosing( WindowEvent e )
                      { System.exit( 0 );
                      }
                   }
                );
    // app.runClient();
             } // end main
          } // end Client Class

         // Server.java
          // Set up a Server that will receive a connection
          // from a client, send a string to the client,
          // and close the connection.
          import java.io.*;
          import java.net.*;
          import java.awt.*;
          import java.awt.event.*;
          import javax.swing.*;

          public class Server1 extends JFrame
          {
             private JTextField enter;
             private JTextArea display;
             ObjectOutputStream output;
             ObjectInputStream input;

          public Server1()
          {
             super( "Server" );

             Container c = getContentPane();

             enter = new JTextField();
             enter.setEnabled( false );
             enter.addActionListener(
                new ActionListener()
                {
                   public void actionPerformed( ActionEvent e )
                   {
                      sendData( e.getActionCommand() );
                   }
                }
             );
             c.add( enter, BorderLayout.NORTH );

             display = new JTextArea();
             c.add( new JScrollPane( display ),
                    BorderLayout.CENTER );

             setSize( 300, 300 );
             show();
          } // end Server constructor

          public void runServer()
          {
                  
             ServerSocket server;
             Socket connection;
             int counter = 1, optionPane;

             try {
    // Create a ServerSocket.
                server = new ServerSocket( 6000, 100 );

                while ( true )
                 {
    // Wait for a connection.
                   display.setText( "Waiting for connection\n" );
                   connection = server.accept();
                   display.append( "Connection " + counter +
                      " received from: " +
                      connection.getInetAddress().getHostName() );

    // Set input and output streams.
                   output = new ObjectOutputStream(
                                connection.getOutputStream() );
                   output.flush();
                   input = new ObjectInputStream(
                               connection.getInputStream() );
                   display.append( "\nGot I/O streams\n" );

    // Process connection.
                   String message =
                      "SERVER>>> Connection successful\n";
                   output.writeObject( message );
                   output.flush();
                   enter.setEnabled( true );

                   do {
                      try {
                         message = (String) input.readObject();
                         display.append( "\n" + message );
                         display.setCaretPosition(
                            display.getText().length() );
                      }
                      catch ( ClassNotFoundException cnfex ) {
                         display.append(
                            "\nUnknown object type received" );
                      }

                      if( message.equals( "CLIENT>>> TRANSFER FILE?" ) )
                      {
                      optionPane = JOptionPane.showConfirmDialog((Component)
                       null, "Do you want to accept the file transfer",
                       "File Transfer", JOptionPane.YES_NO_OPTION );

                      if( optionPane == JOptionPane.YES_NO_OPTION )
                              {
                              output.writeObject( "PRESS 'SEND FILE' BUTTON" );
                                        output.flush();
                                        display.append( "\nWAITING FOR FILE" );
                              }
                              
                              else
                              {
                              output.writeObject( "NO - Do not send file" );
                                        output.flush();
                                        display.append( "\nNO - Do not send file" );
                              }
                      }

                   } while ( !message.equals( "CLIENT>>> quit" ) );

    // Close connection.
                   display.append( "\nUser terminated connection" );
                   enter.setEnabled( false );
                   output.close();
                   input.close();
                   connection.close();

                   ++counter;
                } // end while
             } // end try
             catch ( EOFException eof ) {
                System.out.println( "Client terminated connection" );
             }
             catch ( IOException io ) {
                io.printStackTrace();
             }

          } // end runServer

          private void sendData( String s )
          {
             try {
                output.writeObject( "SERVER>>> " + s );
                output.flush();
                display.append( "\nSERVER>>>" + s );
             }
             catch ( IOException cnfex ) {
                display.append(
                   "\nError writing object" );
             }
          } // end sendData

          public static void main( String args[] )
          {
             Server1 app = new Server1();
             app.addWindowListener(
                new WindowAdapter()
                {
                   public void windowClosing( WindowEvent e )
                   { System.exit( 0 );
                   }
                }
             );
             app.runServer();
           } // end main
          } // end Server Class


  • Next message: Roedy Green: "Re: Client/Server chat program - wait for connection"