Web application chat with Java and Primefaces

Asked

Viewed 528 times

4

Well I would like to ask a question. I have to do a sort of chat where people can talk to each other. It will work like a chat of Facebook or WhatsApp for example, but I have no basis or reference I can search for. This will go to an application Web java-made.

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

2 answers

5

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

This, in turn, is available in the Java EE JSR 356 specification (such specification can be executed in web containers as well, for example, Tomcat and Jetty), Javascript and other languages also implement Websockets, follows 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:

http://www.hascode.com/2013/08/creating-a-chat-application-using-java-ee-7-websockets-and-glassfish-4/

https://tyrus.java.net/ Reference implementation in Java EE

http://javaeesquad.blogspot.com.br/2014/05/chat-application-in-java-ee-7.html

0

Just taking a complementary look at the Chat that Primefaces has in their showcase, follows the link, who knows can help you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.