BomberStudentClient.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. * @author Arthur Brandao
  15. */
  16. public class BomberStudentClient {
  17. protected int portUdp;
  18. protected int portTcp;
  19. protected Broadcast finder;
  20. protected TcpClient socket;
  21. /* --- Constructeurs --- */
  22. public BomberStudentClient(){
  23. this.portUdp = 28624;
  24. this.portTcp = 28642;
  25. this.finder = new Broadcast(this.portUdp);
  26. }
  27. public BomberStudentClient(int portUdp, int portTcp){
  28. this.portUdp = portUdp;
  29. this.portTcp = portTcp;
  30. this.finder = new Broadcast(this.portUdp);
  31. }
  32. /* --- Methodes --- */
  33. public int findServer(){
  34. this.finder.search("i'm a bomberstudent server");
  35. return this.finder.getServers().size();
  36. }
  37. public boolean selectServer(int index){
  38. ArrayList<InetAddress> serv = this.finder.getServers();
  39. if(index <= 0 || index >= serv.size()){
  40. System.err.println("Index invalide");
  41. return false;
  42. }
  43. this.socket = new TcpClient(this.finder.getServers().get(index), this.portTcp);
  44. return this.socket.connect();
  45. }
  46. public boolean send(String method, String ressource, JSONObject param){
  47. //Verif que la methode existe
  48. method = method.toUpperCase();
  49. if(!method.equals("POST") && !method.equals("GET")){
  50. return false;
  51. }
  52. //Creation json pour envoi
  53. JSONObject json = new JSONObject();
  54. json.put("methode", method);
  55. json.put("ressource", ressource);
  56. json.put("param", param);
  57. //Envoi
  58. this.socket.send(json.toString());
  59. return true;
  60. }
  61. public BomberStudentReponse receive(){
  62. String msg = this.socket.receive();
  63. if(msg == null){
  64. return new BomberStudentReponse();
  65. } else {
  66. return new BomberStudentReponse(msg);
  67. }
  68. }
  69. public boolean close(){
  70. return this.socket.close();
  71. }
  72. }