Broadcast via a route on Express

3

I have an endpoint in an application node that when calling should trigger a broadcast to the connected users in the application node. That is, as soon as the user entered the system it would connect through the socket.io and would wait until an external agent called that route so the message would be triggered for whoever was connected. It is possible ? I do not know if I was clear enough. I'm using for this express and socket.io.

    
asked by anonymous 24.09.2015 / 21:06

1 answer

1

No doubt, it is possible. Here's 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);
  });
}

On the client, index.html

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