NetworkHandler.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package control;
  2. import java.io.IOException;
  3. import java.net.DatagramPacket;
  4. import java.net.DatagramSocket;
  5. import java.net.InetAddress;
  6. import java.net.SocketException;
  7. import java.net.UnknownHostException;
  8. import control.button.ButtonHandler;
  9. import control.joystick.JoystickHandler;
  10. public class NetworkHandler implements Runnable{
  11. DatagramSocket udp;
  12. String host;
  13. int port;
  14. boolean running;
  15. Thread t;
  16. byte[] send;
  17. byte[] receive;
  18. ButtonHandler bth;
  19. JoystickHandler jth;
  20. public NetworkHandler(String host, int port, ButtonHandler bth, JoystickHandler jth)
  21. {
  22. this.host = host;
  23. this.port = port;
  24. this.bth = bth;
  25. this.jth = jth;
  26. udp = null;
  27. send = new byte[1024];
  28. receive = new byte[1024];
  29. try {
  30. udp = new DatagramSocket(1112);
  31. } catch (SocketException e) {
  32. e.printStackTrace();
  33. }
  34. running = true;
  35. t = new Thread(this);
  36. t.start();
  37. }
  38. public void setLed(int led, int r, int g , int b)
  39. {
  40. String cmd = "1|" + led + "|" + r + "|" + g + "|" + b + "\n";
  41. send(cmd);
  42. }
  43. public void show(){
  44. String cmd = "0\n";
  45. send(cmd);
  46. }
  47. private void send(String str)
  48. {
  49. send = str.getBytes();
  50. try {
  51. udp.send(new DatagramPacket(send, send.length));
  52. } catch (IOException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. public void close()
  57. {
  58. running = false;
  59. udp.disconnect();
  60. udp.close();
  61. }
  62. @Override
  63. public void run() {
  64. while(running)
  65. {
  66. DatagramPacket receivePacket = new DatagramPacket(receive, receive.length);
  67. try {
  68. udp.receive(receivePacket);
  69. } catch (IOException e) {
  70. e.printStackTrace();
  71. }
  72. String sentence = new String( receivePacket.getData());
  73. System.out.println("RECEIVED: " + sentence);
  74. String[] controls = sentence.split("\\|");
  75. for(int i = 0; i < 7; i++){
  76. if(Integer.parseInt(controls[i]) != ButtonHandler.getButton(i).pressed)
  77. {
  78. System.out.println("PRESS BITCH " + controls[i]);
  79. ButtonHandler.getButton(i).pressed = Integer.parseInt(controls[i]);
  80. if(Integer.parseInt(controls[i]) == 0)
  81. bth.buttonPress(ButtonHandler.getButton(i));
  82. }
  83. }
  84. }
  85. }
  86. }