Organizational Research By

Surprising Reserch Topic

node js socket io broadcast from server rather than from a specific client

node js socket io broadcast from server rather than from a specific client  using -'node.js,'

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

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'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 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.

asked Sep 18, 2015 by loknath.ganji
0 votes

Related Hot Questions

Government Jobs Opening