/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsx; import java.net.InetAddress; import java.util.ArrayList; import org.json.JSONObject; import rsx.tcp.TcpClient; import rsx.udp.Broadcast; /** * Connexion à un server BomberStudent * * @author Arthur Brandao */ public class BomberStudentClient { protected int portUdp; protected int portTcp; protected Broadcast finder; protected TcpClient socket; /* --- Constructeurs --- */ public BomberStudentClient() { this.portUdp = 18624; this.portTcp = 18642; this.finder = new Broadcast(this.portUdp); } public BomberStudentClient(int portUdp, int portTcp) { this.portUdp = portUdp; this.portTcp = portTcp; this.finder = new Broadcast(this.portUdp); } /* --- Methodes --- */ public int findServer() { this.finder.search("i'm a bomberstudent server"); return this.finder.getServers().size(); } public boolean selectServer(int index) { ArrayList serv = this.finder.getServers(); System.out.println(serv.size()); if (!(index >= 0 && index < serv.size())) { System.err.println("Index invalide"); return false; } this.socket = new TcpClient(serv.get(index), this.portTcp); return this.socket.connect(); } public boolean send(String method, String ressource) { return this.send(method, ressource, null); } public boolean send(String method, String ressource, JSONObject param) { //Verif que la methode existe method = method.toUpperCase(); if (!method.equals("POST") && !method.equals("GET")) { return false; } //Creation json pour envoi JSONObject json = new JSONObject(); json.put("methode", method); json.put("ressource", ressource); if (param != null) { json.put("param", param); } //Envoi this.socket.send(json.toString()); return true; } public BomberStudentReponse receive() { String msg = this.socket.receive(); if (msg == null) { return new BomberStudentReponse(); } else { return new BomberStudentReponse(msg); } } public boolean close() { return this.socket.close(); } }