简体   繁体   English

无法从socket.io中的Express路由发出事件

[英]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) 我已经在集群Express(4.11)应用中设置了socket.io(1.3.5),并且可以正常工作(在我的主app.js文件中)

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. 我将io对象传递到路由模块中,以便可以在路由中访问它。

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: 这应该很奇怪,我已经创建了一个可以正常工作的示例,您可以在其中查看如何使用io.emit方法向所有连接的套接字发送消息:

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发射器 ,我不确定它是否与我也在使用集群这一事实有关,但是现在可以使用了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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