Broadcast via an Express route

Asked

Viewed 177 times

3

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

1 answer

1

Without a doubt, yes 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);
  });
}

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.