CommandConnection.jsl 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package DokeosAppShare;
  2. import java.net.*;
  3. import java.io.*;
  4. /**
  5. * Summary description for ConnectionToRelay.
  6. */
  7. public class CommandConnection extends Thread
  8. {
  9. /* COMMANDS */
  10. public static final int SERVER_CONNECTION = 10;
  11. public static final int CLIENT_CONNECTION = 20;
  12. public static final int RELAY_CONNECTION = 30;
  13. Socket relay;
  14. String serverID;
  15. public CommandConnection(String inServerID) throws IOException
  16. {
  17. serverID = inServerID;
  18. relay = new Socket(Config.getRelayHostName(), Config.getRelayPort());
  19. this.setDaemon(true);
  20. }
  21. public void run()
  22. {
  23. try
  24. {
  25. InputStream in = relay.getInputStream();
  26. OutputStream out = relay.getOutputStream();
  27. writeCommand(out, SERVER_CONNECTION, serverID);
  28. for (; ; )
  29. {
  30. //Wait command from relay
  31. System.out.println("Waiting command from relay...");
  32. int command = in.read();
  33. System.out.println("Command receive : " + command);
  34. if (command == RELAY_CONNECTION)
  35. {
  36. String connServerId = readCommandParam(in);
  37. System.out.println("relay try connection to : " + connServerId);
  38. if (connServerId.equals(serverID))
  39. {
  40. try
  41. {
  42. new ConnectionToRelay(serverID);
  43. }
  44. catch (Exception ex)
  45. {
  46. System.out.println("Exception on ConnectionToRelay instanciation");
  47. ex.printStackTrace();
  48. }
  49. }
  50. else
  51. {
  52. System.out.println("bad server name : " + connServerId);
  53. }
  54. }
  55. }
  56. }
  57. catch (IOException ex)
  58. {
  59. System.out.println("Exception in CommandConnection listener thread");
  60. ex.printStackTrace();
  61. }
  62. finally
  63. {
  64. try { relay.close(); }
  65. catch (Exception ex) { }
  66. //TODO Exit application
  67. }
  68. }
  69. public static String readCommandParam(InputStream in) throws IOException
  70. {
  71. int size = in.read();
  72. byte[] data = new byte[size];
  73. in.read(data);
  74. return new String(data);
  75. }
  76. public static void writeCommand(OutputStream out, int command, String param) throws IOException
  77. {
  78. out.write(command);
  79. byte[] data = param.getBytes();
  80. out.write(data.length);
  81. out.write(data);
  82. }
  83. }