Can't emit event from Express route in socket.io

1.2k views Asked by At

I have set up socket.io (1.3.5) in my clustered express (4.11) app and have this working (in my main app.js file)

io.on('connection', function (socket) {
    io.emit('message', 'ja');
});

This, console logs out in the browser and works fine. Here's what I want to do:

I want to emit a message when an action has been performed on the server side, to notify the user that there is something new to see.

I am passing the io object in to my routes module, so that I have access to it within my routes.

When I try this:

router.post('/entries.json',(req, res, next) => {
    io.emit('message', 'nein')
});

I don't get any errors, it just fails silently. I feel like its something fairly fundamental that I'm just not seeing. What can I do to make this work?

3

There are 3 answers

1
Guillermo Mansilla On

You're calling the wrong method, try this:

io.sockets.emit('message', 'nein');
0
Wilson On

It should be working that's weird, I have created an example that is working where you can see how I am using the io.emit method to send a message to all sockets connected:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

app.get('/', function(req, res) {
    // you can use io.sockets.emit or io.emit, it is the same.                                                                
    io.emit('message', 'there is something new');
    res.end();
});

io.on('connection', function(socket) {
    console.log('new connection');
});

server.listen(4040, function() {
    console.log('server up and running at 4040 port');
});
0
user3240114 On

Turns out I had to use socket.io emitter, I'm not sure if it was related to the fact that I was using clusters as well, but it works now!