Websocket send data all client in playframework 2

2019-04-17 06:28发布

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

1条回答
叛逆
2楼-- · 2019-04-17 07:04

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):

Map<String, WebSocket.Out<JsonNode>> members = new HashMap<String, WebSocket.Out<JsonNode>>();

Then the register is done here:

members.put(join.username, join.channel);

And a message is sent to all clients, it is done by iterating through all registered Webscokets:

for(WebSocket.Out<JsonNode> channel: members.values()) {

    ObjectNode event = Json.newObject();
    event.put("kind", kind);
    event.put("user", user);
    event.put("message", text);

    ArrayNode m = event.putArray("members");
    for(String u: members.keySet()) {
        m.add(u);
    }

    channel.write(event);
}
查看更多
登录 后发表回答