All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.jarch.faces.websocket.SessionWebSocket Maven / Gradle / Ivy

package br.com.jarch.faces.websocket;

import br.com.jarch.util.LogUtils;

import javax.enterprise.context.ApplicationScoped;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

@ApplicationScoped
public class SessionWebSocket implements Serializable {

    private Set remoteUsers = new HashSet<>();

    public boolean add(Session remoteUser) {
        return this.remoteUsers.add(remoteUser);
    }

    public void send(String message) {
        send(null, message);
    }

    public void send(Session sessionFrom, String message) {
        for (Session sessionTo : remoteUsers) {
            if (sessionFrom != null
                    && sessionTo != null
                    && sessionFrom.getQueryString() != null
                    && !sessionFrom.getQueryString().equals(sessionTo.getQueryString())) {
                continue;
            }

            if (sessionFrom != null) {
                LogUtils.warning("sessionFrom.getQueryString(): " + sessionFrom.getQueryString());
            }

            if (sessionTo != null) {
                LogUtils.warning("sessionTo.getQueryString(): " + sessionTo.getQueryString());
            }

            if (sessionTo.isOpen()) {
                try {
                    RemoteEndpoint.Basic basicRemote = sessionTo.getBasicRemote();
                    basicRemote.sendText(message);
                    LogUtils.generate("Mensagem enviada WebSocket " + message);
                } catch (IOException e) {
                    LogUtils.warning("Não foi possivel enviar mensagem para um cliente");
                    e.printStackTrace();
                }
            } else {
                LogUtils.warning("Cliente WebSocket não está mais aberto");
            }
        }
    }

    public boolean remove(Session session) {
        return remoteUsers.remove(session);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy