简体   繁体   中英

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

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?

您调用了错误的方法,请尝试以下操作:

io.sockets.emit('message', 'nein');

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');
});

原来我必须使用socket.io发射器 ,我不确定它是否与我也在使用集群这一事实有关,但是现在可以使用了!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM