BomberStudentClient.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package rsx;
  7. import java.net.InetAddress;
  8. import java.util.ArrayList;
  9. import org.json.JSONObject;
  10. import rsx.tcp.TcpClient;
  11. import rsx.udp.Broadcast;
  12. /**
  13. * Connexion à un server BomberStudent
  14. *
  15. * @author Arthur Brandao
  16. */
  17. public class BomberStudentClient {
  18. protected int portUdp;
  19. protected int portTcp;
  20. protected Broadcast finder;
  21. protected TcpClient socket;
  22. /* --- Constructeurs --- */
  23. public BomberStudentClient() {
  24. this.portUdp = 18624;
  25. this.portTcp = 18642;
  26. this.finder = new Broadcast(this.portUdp);
  27. }
  28. public BomberStudentClient(int portUdp, int portTcp) {
  29. this.portUdp = portUdp;
  30. this.portTcp = portTcp;
  31. this.finder = new Broadcast(this.portUdp);
  32. }
  33. /* --- Methodes --- */
  34. public int findServer() {
  35. this.finder.search("i'm a bomberstudent server");
  36. return this.finder.getServers().size();
  37. }
  38. public boolean selectServer(int index) {
  39. ArrayList<InetAddress> serv = this.finder.getServers();
  40. System.out.println(serv.size());
  41. if (!(index >= 0 && index < serv.size())) {
  42. System.err.println("Index invalide");
  43. return false;
  44. }
  45. this.socket = new TcpClient(serv.get(index), this.portTcp);
  46. return this.socket.connect();
  47. }
  48. public boolean send(String method, String ressource) {
  49. return this.send(method, ressource, null);
  50. }
  51. public boolean send(String method, String ressource, JSONObject param) {
  52. //Verif que la methode existe
  53. method = method.toUpperCase();
  54. if (!method.equals("POST") && !method.equals("GET")) {
  55. return false;
  56. }
  57. //Creation json pour envoi
  58. JSONObject json = new JSONObject();
  59. json.put("methode", method);
  60. json.put("ressource", ressource);
  61. if (param != null) {
  62. json.put("param", param);
  63. }
  64. //Envoi
  65. this.socket.send(json.toString());
  66. return true;
  67. }
  68. public BomberStudentReponse receive() {
  69. String msg = this.socket.receive();
  70. if (msg == null) {
  71. return new BomberStudentReponse();
  72. } else {
  73. return new BomberStudentReponse(msg);
  74. }
  75. }
  76. public boolean close() {
  77. return this.socket.close();
  78. }
  79. }