简体   繁体   中英

Socket.io serverside broadcast

I want to update an array on the server and broadcast it to all clients. The problem I am facing is that I need the client parameter to broadcast. On the server:

    var socket = io.listen(8000);
    var plateaus = [];

    setInterval(function () {
        plateaus.push('new data');
       -- send the updated array to all clients --
    }, 1000);

    socket.sockets.on("connection", setEventListeners);

    function setEventListeners(client) 
       // loadExistingPlayer(client); <- normally I use the client param
    }

How do I broadcast the updated array? Many thanks!

answer on my own question (hope I will help anyone in the future).

You can store the client parameter in an array and access it anytime:

var socket = io.listen(8000);
var plateaus = [];
var clients = []

setInterval(function () {
    plateaus.push('new data');
    for(var i = 0; i < clients.length; i++){
       clients[i].emit('updata all clients',  plateaus)
    }
}, 1000);

socket.sockets.on("connection", setEventListeners);

function setEventListeners(client) 
   console.log('new client');
   clients.push(client);
}

After you connect your client, wouldn't you just emit an event from your server and your client could listen to that event with on(event, cb) ?

From the Docs: http://socket.io/docs/

Server:

var io = require('socket.io')(server);

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

Client:

var socket = io('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM