package br.com.casadocodigo.loja.websockets;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ApplicationScoped;
import javax.websocket.Session;
@ApplicationScoped
public class UsuarioSession {
private List<Session> sessions = new ArrayList<>();
public void Add(Session session) {
sessions.add(session);
System.out.println("Usuário "+session.getId()+ " adicionado!");
for (Session sessionlist : sessions) {
System.out.println("Usuário "+sessionlist.getId());
}
}
public void Remove(Session session) {
sessions.remove(session);
}
public List<Session> getUsuarios() {
return sessions;
}
}
package br.com.casadocodigo.loja.websockets;
import java.io.IOException;
import java.util.List;
import javax.inject.Inject;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import br.com.casadocodigo.loja.models.Promo;
@ServerEndpoint(value = "/canal/promos")
public class PromosEndpoint {
@Inject
private UsuarioSession usuarios;
@OnOpen
public void onMessage(Session session) {
usuarios.Add(session);
}
public void send(Promo promo) {
List<Session> sessions = usuarios.getUsuarios();
for (Session session : sessions) {
System.out.println(session.getId());
if (session.isOpen()) {
try {
session.getBasicRemote().sendText(promo.toJson());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void onClose(Session session) {
usuarios.Remove(session);
System.out.println("Sessão removida!");
}
}