Reputation: 1773
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!
Upvotes: 1
Views: 82
Reputation: 1773
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);
}
Upvotes: 1
Reputation: 630
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' });
});
Upvotes: 0