Guest User

Client.java

a guest
Oct 21st, 2014
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.23 KB | None | 0 0
  1. // Fig. 18.5: Client.java
  2. // Client that reads and displays information sent from a Server.
  3. import java.io.*;
  4. import java.net.*;
  5. import java.awt.*;
  6. import java.awt.event.*;
  7. import javax.swing.*;
  8.  
  9. public class Client extends JFrame {
  10.    private JTextField enterField;
  11.    private JTextArea displayArea;
  12.    private ObjectOutputStream output;
  13.    private ObjectInputStream input;
  14.    private String message = "";
  15.    private String chatServer;
  16.    private Socket client;
  17.  
  18.    // initialize chatServer and set up GUI
  19.    public Client( String host )
  20.    {
  21.       super( "Client" );
  22.  
  23.       chatServer = host; // set server to which this client connects
  24.  
  25.       Container container = getContentPane();
  26.  
  27.       // create enterField and register listener
  28.       enterField = new JTextField();
  29.       enterField.setEditable( false );
  30.       enterField.addActionListener(
  31.          new ActionListener() {
  32.  
  33.             // send message to server
  34.             public void actionPerformed( ActionEvent event )
  35.             {
  36.                sendData( event.getActionCommand() );
  37.                enterField.setText( "" );
  38.             }
  39.          }  
  40.       );
  41.  
  42.       container.add( enterField, BorderLayout.NORTH );
  43.  
  44.       // create displayArea
  45.       displayArea = new JTextArea();
  46.       container.add( new JScrollPane( displayArea ),
  47.          BorderLayout.CENTER );
  48.  
  49.       setSize( 300, 150 );
  50.       setVisible( true );
  51.  
  52.    } // end Client constructor
  53.  
  54.    // connect to server and process messages from server
  55.    private void runClient()
  56.    {
  57.       // connect to server, get streams, process connection
  58.       try {
  59.          connectToServer(); // Step 1: Create a Socket to make connection
  60.          getStreams();      // Step 2: Get the input and output streams
  61.          processConnection(); // Step 3: Process connection
  62.       }
  63.  
  64.       // server closed connection
  65.       catch ( EOFException eofException ) {
  66.          System.err.println( "Client terminated connection" );
  67.       }
  68.  
  69.       // process problems communicating with server
  70.       catch ( IOException ioException ) {
  71.          ioException.printStackTrace();
  72.       }
  73.  
  74.       finally {
  75.          closeConnection(); // Step 4: Close connection
  76.       }
  77.  
  78.    } // end method runClient
  79.  
  80.    // connect to server
  81.    private void connectToServer() throws IOException
  82.    {      
  83.       displayMessage( "Attempting connection\n" );
  84.  
  85.       // create Socket to make connection to server
  86.       client = new Socket( InetAddress.getByName( chatServer ), 12345 );
  87.  
  88.       // display connection information
  89.       displayMessage( "Connected to: " +
  90.          client.getInetAddress().getHostName() );
  91.    }
  92.  
  93.    // get streams to send and receive data
  94.    private void getStreams() throws IOException
  95.    {
  96.       // set up output stream for objects
  97.       output = new ObjectOutputStream( client.getOutputStream() );      
  98.       output.flush(); // flush output buffer to send header information
  99.  
  100.       // set up input stream for objects
  101.       input = new ObjectInputStream( client.getInputStream() );
  102.  
  103.       displayMessage( "\nGot I/O streams\n" );
  104.    }
  105.  
  106.    // process connection with server
  107.    private void processConnection() throws IOException
  108.    {
  109.       // enable enterField so client user can send messages
  110.       setTextFieldEditable( true );
  111.  
  112.       do { // process messages sent from server
  113.  
  114.          // read message and display it
  115.          try {
  116.             message = ( String ) input.readObject();
  117.             displayMessage( "\n" + message );
  118.          }
  119.  
  120.          // catch problems reading from server
  121.          catch ( ClassNotFoundException classNotFoundException ) {
  122.             displayMessage( "\nUnknown object type received" );
  123.          }
  124.  
  125.       } while ( !message.equals( "SERVER>>> TERMINATE" ) );
  126.  
  127.    } // end method processConnection
  128.  
  129.    // close streams and socket
  130.    private void closeConnection()
  131.    {
  132.       displayMessage( "\nClosing connection" );
  133.       setTextFieldEditable( false ); // disable enterField
  134.  
  135.       try {
  136.          output.close();
  137.          input.close();
  138.          client.close();
  139.       }
  140.       catch( IOException ioException ) {
  141.          ioException.printStackTrace();
  142.       }
  143.    }
  144.  
  145.    // send message to server
  146.    private void sendData( String message )
  147.    {
  148.       // send object to server
  149.       try {
  150.          output.writeObject( "CLIENT>>> " + message );
  151.          output.flush();
  152.          displayMessage( "\nCLIENT>>> " + message );
  153.       }
  154.  
  155.       // process problems sending object
  156.       catch ( IOException ioException ) {
  157.          displayArea.append( "\nError writing object" );
  158.       }
  159.    }
  160.  
  161.    // utility method called from other threads to manipulate
  162.    // displayArea in the event-dispatch thread
  163.    private void displayMessage( final String messageToDisplay )
  164.    {
  165.       // display message from GUI thread of execution
  166.       SwingUtilities.invokeLater(
  167.          new Runnable() {  // inner class to ensure GUI updates properly
  168.  
  169.             public void run() // updates displayArea
  170.             {
  171.                displayArea.append( messageToDisplay );
  172.                displayArea.setCaretPosition(
  173.                   displayArea.getText().length() );
  174.             }
  175.  
  176.          }  // end inner class
  177.  
  178.       ); // end call to SwingUtilities.invokeLater
  179.    }
  180.  
  181.    // utility method called from other threads to manipulate
  182.    // enterField in the event-dispatch thread
  183.    private void setTextFieldEditable( final boolean editable )
  184.    {
  185.       // display message from GUI thread of execution
  186.       SwingUtilities.invokeLater(
  187.          new Runnable() {  // inner class to ensure GUI updates properly
  188.  
  189.             public void run()  // sets enterField's editability
  190.             {
  191.                enterField.setEditable( editable );
  192.             }
  193.  
  194.          }  // end inner class
  195.  
  196.       ); // end call to SwingUtilities.invokeLater
  197.    }
  198.  
  199.    public static void main( String args[] )
  200.    {
  201.       Client application;
  202.  
  203.       if ( args.length == 0 )
  204.          application = new Client( "127.0.0.1" );
  205.       else
  206.          application = new Client( args[ 0 ] );
  207.  
  208.       application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  209.       application.runClient();
  210.    }
  211.  
  212. } // end class Client
  213.  
  214. /**************************************************************************
  215.  * (C) Copyright 1992-2003 by Deitel & Associates, Inc. and               *
  216.  * Prentice Hall. All Rights Reserved.                                    *
  217.  *                                                                        *
  218.  * DISCLAIMER: The authors and publisher of this book have used their     *
  219.  * best efforts in preparing the book. These efforts include the          *
  220.  * development, research, and testing of the theories and programs        *
  221.  * to determine their effectiveness. The authors and publisher make       *
  222.  * no warranty of any kind, expressed or implied, with regard to these    *
  223.  * programs or to the documentation contained in these books. The authors *
  224.  * and publisher shall not be liable in any event for incidental or       *
  225.  * consequential damages in connection with, or arising out of, the       *
  226.  * furnishing, performance, or use of these programs.                     *
  227.  *************************************************************************/
Advertisement
Add Comment
Please, Sign In to add comment