39 lines
1.1 KiB
Java
39 lines
1.1 KiB
Java
package ch.usi.inf.sa4.sanmarinoes.smarthut.socket;
|
|
|
|
import com.google.gson.Gson;
|
|
import com.google.gson.JsonObject;
|
|
import java.io.IOException;
|
|
import java.util.*;
|
|
import javax.websocket.*;
|
|
|
|
public class SensorSocketEndpoint extends Endpoint {
|
|
|
|
private Gson gson = new Gson();
|
|
|
|
private Set<Session> clients = Collections.synchronizedSet(new HashSet<>());
|
|
|
|
public Set<Session> getClients() {
|
|
return clients;
|
|
}
|
|
|
|
public int broadcast(JsonObject message) throws IOException, EncodeException {
|
|
for (Session session : clients) {
|
|
System.out.println(message);
|
|
session.getBasicRemote().sendObject(message);
|
|
}
|
|
return clients.size();
|
|
}
|
|
|
|
@Override
|
|
public void onOpen(Session session, EndpointConfig config) {
|
|
final JsonObject test = new JsonObject();
|
|
test.addProperty("ciao", "mamma");
|
|
try {
|
|
session.getBasicRemote().sendText(gson.toJson(test));
|
|
clients.add(session);
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
}
|