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 RepeatConnectionHandler implements ConnectionHandler, Runnable {
15 /***
16 * The connection with the client connected to the server.
17 */
18 private Connection clientConnection;
19
20 /***
21 * The reader from the connection with the client connected to the server.
22 */
23 private ResponseReader reader = new ResponseReader();
24
25 /***
26 * The connection with the server the server that the instance handles the connection
27 * is connected.
28 */
29 private Connection serverConnection;
30
31
32 /***
33 * The constructor.
34 * @param hostName the name of the host the instance connects to.
35 * @param portNumber the port number through the instance is connected.
36 */
37 public RepeatConnectionHandler(String hostName, int portNumber) {
38 serverConnection = new Connection(hostName, portNumber);
39 try {
40 serverConnection.open();
41
42 new Thread(this).start();
43 }
44 catch (IOException ioe) {
45 System.out.println("Failed to open a connection to the server");
46 ioe.printStackTrace();
47 }
48 }
49
50
51
52
53
54
55
56 /***
57 * Handles the specified connection.
58 * @param connection the connection to handle.
59 */
60 public void handleConnection(Connection connection) {
61
62 clientConnection = connection;
63 }
64
65
66
67
68 /***
69 *
70 */
71 public void run() {
72 String object = null;
73
74 while (true) {
75
76 try {Thread.sleep(1000);} catch (Exception e) {e.printStackTrace();}
77
78 System.out.println("on bloucle et clientConnection = " + clientConnection);
79
80 if (clientConnection != null) {
81 System.out.println("On attend un obj");
82
83 object = reader.read(clientConnection.getInputStream());
84
85 if (object != null) {
86 try {
87 System.out.println("on a lu obj ====> envoie au serveur");
88 serverConnection.getOutputStream().write(object.getBytes());
89
90 System.out.println("on attends reponse server");
91 object = reader.read(serverConnection.getInputStream());
92
93 if (object != null) {
94 try {
95 System.out.println("on envoie reponse au client");
96 clientConnection.getOutputStream().write(object.getBytes());
97 }
98 catch (IOException ioe) {
99 System.out.println("Failed to send back response to the client");
100 ioe.printStackTrace();
101 }
102 }
103 }
104 catch (IOException ioe) {
105 System.out.println("Failed to piped the object to the server");
106 ioe.printStackTrace();
107 }
108 }
109 }
110 }
111 }
112 }