View Javadoc

1   package fr.ove.clientserver;
2   
3   import fr.ove.utils.Connection;
4   import fr.ove.utils.ConnectionHandler;
5   import fr.ove.openmath.mathematica.ResponseReader;
6   import java.io.IOException;
7   
8   /***
9   * A ConnectionHandler implementation.<BR>
10  * This connection handler is used with a server which connects to an another one.
11  * The objects sent from a connected client are sent to the server the server whose
12  * instance deals the conections is connected.
13  */
14  public class EchoConnectionHandler implements ConnectionHandler {
15      Connection connection;
16      /***
17      * The constructor.
18      */
19      public EchoConnectionHandler() {
20      }
21      
22      // #################################
23      // ### Interfaces Implementation ###
24      // #################################    
25  
26      // ConnectionHandler interface
27  
28      /***
29      * Handles the specified connection.
30      * @param connection the connection to handle.
31      */
32      public void handleConnection(Connection connection) {
33          new Echoer(connection);
34      }
35      
36      /***
37      *
38      */
39      private class Echoer implements Runnable {
40          private Connection connection;
41          private ResponseReader reader = new ResponseReader();
42          
43          public Echoer(Connection connection) {
44              this.connection = connection;
45              new Thread(this).start();
46          }
47          // Runnable interface
48  
49          /***
50          *
51          */
52          public void run() {
53              String object = null;
54              
55              while (true) {
56                  try {Thread.sleep(100);} catch (Exception e) {e.printStackTrace();}
57                  if (connection != null) {
58                      // Read the object sent by the client.
59                      object = reader.read(connection.getInputStream());
60                      
61                      //try {Thread.sleep(1000);} catch (Exception e) {e.printStackTrace();}
62                      
63                      // if we got it, send it to the server
64                      if (object != null) {
65                          try {
66                              connection.getOutputStream().write(object.getBytes());
67                          }
68                          catch (IOException ioe) {
69                              System.out.println("Failed to send back the object");
70                              ioe.printStackTrace();
71                          }
72                      }
73                  }
74              }
75          }
76      }
77  }