16
votes

I'm building a simple system like a realtime news feed, using node.js + socket.io.

Since this is a "read-only" system, clients connect and receive data, but clients never actually send any data of their own. The server generates the messages that needs to be sent to all clients, no client generates any messages; yet I do need to broadcast.

The documentation for socket.io's broadcast (end of page) says

To broadcast, simply add a broadcast flag to emit and send method calls. Broadcasting means sending a message to everyone else except for the socket that starts it.

So I currently capture the most recent client to connect, into a variable, then emit() to that socket and broadcast.emit() to that socket, such that this new client gets the new data and all the other clients. But it feels like the client's role here is nothing more than a workaround for what I thought socket.io already supported.

Is there a way to send data to all clients based on an event initiated by the server?

My current approach is roughly:

var socket;

io.sockets.on("connection", function (s) {
  socket = s;
});

/* bunch of real logic, yadda yadda ... */

myServerSideNewsFeed.onNewEntry(function (msg) {
  socket.emit("msg", { "msg" : msg });
  socket.broadcast.emit("msg", { "msg" : msg });
});

Basically the events that cause data to require sending to the client are all server-side, not client-side.

2

2 Answers

21
votes

Why not just do like below?

io.sockets.emit('hello',{msg:'abc'});
5
votes

Since you are emitting events only server side, you should create a custom EventEmitter for your server.

var io = require('socket.io').listen(80);
    events = require('events'),
    serverEmitter = new events.EventEmitter();

io.sockets.on('connection', function (socket) {
  // here you handle what happens on the 'newFeed' event
  // which will be triggered by the server later on
  serverEmitter.on('newFeed', function (data) {
    // this message will be sent to all connected users
    socket.emit(data);
  });
});

// sometime in the future the server will emit one or more newFeed events
serverEmitter.emit('newFeed', data);

Note: newFeed is just an event example, you can have as many events as you like.

Important

The solution above is better also because in the future you might need to emit certain messages only to some clients, not all (thus need conditions). For something simpler (just emit a message to all clients no matter what), io.sockets.broadcast.emit() is a better fit indeed.