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