Source of Client.java


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