1
votes

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.

1
have you tried with socket.broadcast.emit('yourMessage') ? - Sparw
@Sparw socket.broadcast.emit must be in io.on and run when a client connected. All i want is run this function every 5 seconds even server has no client connection. - Marijke Buurlage
Why do you want to send broadcast if there is no connected client ? - Sparw

1 Answers

0
votes

I found a way to do this :

io.on('connection', function(socket) {
   // ... do you stuff
});

setInterval(function() {
   io.local.emit('yourMessage');
}, 3000);

EDIT

More information on Socket.IO Documentation

Hope it helps.