i need help to understand WS in playframework
i have the next code in my controller
public static WebSocket<String> sockHandler() {
return new WebSocket<String>() {
// Se llama para establecer el WS
public void onReady(WebSocket.In<String> in, WebSocket.Out<String> out) {
//por cada evento recivido por el socket
// Se regitra una llamada para el procesamiento de los eventos
in.onMessage(new Callback<String>() {
public void invoke(String event) {
//Logger.info(event)
System.out.println("este es el event "+event);
}
});
// write out a greeting
out.write("Hola a todos");
}
};
}
in my view, i have:
<script type="text/javascript" charset="utf-8">
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var sock = new WS("@routes.Application.sockHandler().webSocketURL(request)")
$('button.send').click(function() {
console.log('entro al click');
sendMessage();
});
var sendMessage = function() {
sock.send("llamando controller");
}
var receiveEvent= function(event) {
$('.greeting').append(event.data);
alert('entro');
}
sock.onmessage=receiveEvent;
})
</script>
I need to always print the alert('entro') on all clients when a client sends an action.
Excuse my English, but I speak Spanish.
thank you very much
In your code, you are writing a response to the actually created Websocket (ie the actual Websocket between the calling client and the server). You have to know that each client has his own Websocket.
If you want to write something to each client, you have to persist all the created Websockets somewhere. In the Play sample, it is done with these parts of code:
A Map containing all Websockets (there outputs actually):
Then the register is done here:
And a message is sent to all clients, it is done by iterating through all registered Webscokets: