koa-websocket icon indicating copy to clipboard operation
koa-websocket copied to clipboard

[ASK] How to use broadcast server API

Open prakasa1904 opened this issue 6 years ago • 2 comments

I cant using broadcast API from here. Any one know how to use brodcast to send message to all clients connected ?

prakasa1904 avatar Nov 12 '18 04:11 prakasa1904

seems this lib is not exposing related api from ws

noru avatar Jan 03 '19 15:01 noru

we can write like this:

app.ws.use((ctx) => {

  /*
   * `ctx` is the regular koa context created from the `ws`
   * onConnection `socket.upgradeReq` object.
   */
  ctx.websocket.broadcast = function(data) {
    app.ws.server.clients.forEach(function each(client) {
      client.send(data);
    });
  };

  // the websocket is added to the context on `ctx.websocket`.
  ctx.websocket.on('message', function(message) {
    // do something with the message from client
    ctx.websocket.broadcast('something');
  });
});

Joey-Wong avatar May 12 '19 08:05 Joey-Wong