NetworkHandler.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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();
  31. udp.connect(InetAddress.getByName(host), port);
  32. } catch (SocketException | UnknownHostException e) {
  33. e.printStackTrace();
  34. }
  35. running = true;
  36. t = new Thread(this);
  37. t.start();
  38. }
  39. public void setLed(int led, int r, int g , int b)
  40. {
  41. String cmd = "1|" + led + "|" + r + "|" + g + "|" + b + "\n";
  42. send(cmd);
  43. }
  44. public void show(){
  45. String cmd = "0\n";
  46. send(cmd);
  47. }
  48. private void send(String str)
  49. {
  50. send = str.getBytes();
  51. try {
  52. udp.send(new DatagramPacket(send, send.length));
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. public void close()
  58. {
  59. running = false;
  60. udp.disconnect();
  61. udp.close();
  62. }
  63. @Override
  64. public void run() {
  65. while(running)
  66. {
  67. DatagramPacket pckg = new DatagramPacket(receive, receive.length);
  68. try {
  69. udp.receive(pckg);
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. }
  73. String str = new String(pckg.getData());
  74. System.out.println(str);
  75. }
  76. }
  77. }