I have node.js socket.io server. I want to send a message to all clients every 5 seconds.
Here my process so far:
var express = require('express');
var app = express();
var path = require('path');
var server = require('http').createServer(app);
var io = require('../..')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
app.use(express.static(path.join(__dirname, 'public')));
function PingPong(socket) {
console.log('Send: Ping Pong, Number of Users: %d', numUsers);
socket.emit('ping pong', {
message: numUsers
});
}
io.on('connection', function (socket) {
var addedUser = false;
numUsers++;
socket.on('ping pong', function (data) {
console.log('Coming Data: Ping Pong');
});
setInterval(PingPong, 3000, socket);
...
});
I'm calling PingPong func and every 5 seconds it sends 'ping pong' to client which is connected.
Is there any way doing this on top, i mean not in 'io.on('connection', ..)'
I wanna do it like this:
function PingPong() {
console.log('Send: Ping Pong, Number of Users: %d', numUsers);
io.emit('ping pong', { //io.emit or io.broadcast.emit instead of socket.emit
message: numUsers
});
}
instead of socket.emit; i wanna use something like io.emit or io.broadcast.emit for sending to all clients at the same time.
Whats your opinion to do it correctly?
Edit: I wanna send send message to clients even server has no clients. I mean io.on(...) run when a client connected. But i want run this function globally and not only when a client connected.