javascript – Broadcast via a route in Express

Question:

I have an endpoint in a node application that when called should trigger a broadcast to the users connected to the node application. In other words, as soon as the user entered the system, he would connect through socket.io and would wait until an external agent called this route so that the message could be sent to whoever was connected. It is possible ? I don't know if I was clear enough. I'm using express and socket.io for this.

Answer:

Without a doubt, it is possible. See an example:

On the server, app.js

var _   = require('lodash');
var app = require('express').createServer();
var io  = require('socket.io')(app);

app.listen(80);

var sockets = {};

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html');
});

app.post('/oi', function(req, res) {
  enviaParaTodos(req.body);
});

io.on('connection', guardaConexao);

function guardaConexao(socket) {
  socket.on('error', console.log);
  socket.on('disconnect', function() {
    delete sockets[socket.id];
  });
  sockets[socket.id] = socket;
}

function enviaParaTodos(dados) {
  _.forOwn(sockets, function (socket, id) {
    socket.emit('oi', dados);
  });
}

Client no, index.html

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('oi', alert);
</script>
Scroll to Top