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