import java.util.HashMap; import java.util.Map; import org.java_websocket.WebSocket; public class Game { public final String id; public final WebSocket host; private final Map<String,WebSocket> clients; public Game(String id, WebSocket host) { this.id = id; this.host = host; this.clients = new HashMap<String,WebSocket>(); } void handleMessage(WebSocket socket, String message){ if (socket==this.host) { String[] parts = message.split(" ",3); WebSocket client = clients.get(parts[1]); client.send("message "+parts[2]); System.out.println("message from host "+this.id+" to player "+parts[1]+": "+parts[2]); }else { this.host.send("message "+getClientID(socket)+" "+message.split(" ",2)[1]); System.out.println("message from player "+getClientID(socket)+" to host "+this.id+": "+message.split(" ",2)[1]); } } boolean hasClient(WebSocket client){ return clients.containsValue(client); } void addClient(WebSocket client) { String id = genID(6); while (clients.containsKey(id)) { id = genID(6); } clients.put(id,client); this.host.send("join "+id); } void removeClient(WebSocket client){ clients.values().remove(client); } private String getClientID(WebSocket client) { for (String id:clients.keySet()) { if (clients.get(id)==client) { return id; } } return null; } static String genID() { return genID(8); } static String genID(int n) { String id = ""; for (int i=0;i<8;i++) { char c = (char)(Math.random()*62); id += (char)(c+(c<10?'0':(c<36?'a'-10:'A'-36))); } return id; } }