Doubt about web application chat with Java and PrimeFaces

4

Well, I'd like to ask a question. I have to make some kind of chat where people can talk to each other. It will work just like a chat of Facebook or WhatsApp for example, but I do not have any database or reference that I can search. This will go to a Web application made with Java.

Is it possible to do this, for example, with PrimeFaces or JavaScript ? Could you give me some links where I can research this?

    
asked by anonymous 24.06.2015 / 19:15

2 answers

5

It is possible to do according to some technologies or services of asynchronous communication, as:

This is available in the JSR 356 specification of Java EE (such specification can be executed in Web containers also, for example, Tomcat and Jetty), JavaScript and other languages also implement WebSockets, following a basic example :

Server

@ServerEndpoint(value = "/chat/{sala}")
public class ChatEndpoint {
    private final Logger log = Logger.getLogger(getClass().getName());

    @OnOpen
    public void open(final Session session, @PathParam("sala") final String sala)   {
      log.info("Sessão aberta para sala: " + sala);
      session.getUserProperties().put("sala", sala);
    }

    @OnMessage
    public void onMessage(final Session session, final String mensagem) {
      String sala= (String) session.getUserProperties().get("sala");
      try {
        for (Session s : session.getOpenSessions()) {
            if (s.isOpen()
                    && sala.equals(s.getUserProperties().get("sala"))) {
                s.getBasicRemote().sendText(mensagem);
            }
        }
      } catch (IOException | EncodeException ex) {
        log.log(Level.WARNING, "onMessage falhou", ex);
      }
    }
}

JavaScript Client

<script>
    var wSocket = new WebSocket("ws://hostname:8080/chat/sala3");
    var browserSupport = ("WebSocket" in window);

    function initializeReception() {
        if (browserSupport) {
            wSocket.onopen = function () {};
        }            
    }

    function enviar(mensagem) {
        wSocket.send(mensagem)
    }

    wSocket.onmessage = function (event) {
        var mensagemRecebida = event.data;
        console.log(mensagemRecebida);
    };

    wSocket.onclose = function () {};
</script>

Some useful links:

link

link Reference implementation in Java EE

link

    
24.06.2015 / 20:00
0

Just giving a compliment of a look at the Chat that Primefaces has in their showcase, follow the link , maybe you can help.

    
25.06.2015 / 14:29