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