Advertisement
Guest User

Server.java

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