Socket io从express controller方法向客户端发送消息 [英] Socket io emit message to client from express controller method

查看:204
本文介绍了Socket io从express controller方法向客户端发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道通常你会有 app.js 创建套接字服务器,并将该实例传递给您的路由器,这又可以将其传递给控制器​​方法。如下所示( Socket.io从Express控制器发出



但是,我有一个控制器方法,需要向任何正在侦听的客户端发出进度,但是这种方法可以从许多不同的路由和其他控制器执行,而我在这个应用程序的所有其他部分,我真的不得不通过引用 socket



是有一个更好的方法吗?



我在想一些像$ code> socketio 帮助模块。 app.js 模块将它引用到 io ,可以稍后检索....



app.js

  var io = ( 'socket.io')听(服务器); 
require('./ helpers / socketio')。set(io);

helpers / socketio.js

  var io = null; 

exports.set = function(socketio){
io = socketio;
}

exports.get = function(){
return io;
}

然后只要你在应用程序中需要它。

  var io = require('./ helpers / socketio')。get(); 
io.emit('message',{a:1,b:2});

有没有更清洁的方法来做到这一点?很明显,它可以返回null,你必须检查。它只是感觉不到....

解决方案


模块第一次被缓存它们被加载。


其实你可以在 helper / socketio.js
尽管您从其他文件调用 require() socketio.js ,node.js将执行代码在该文件上只有一次。



你可以看节点文档


I know that usually you would have app.js create the socket server, and pass that instance down to your router, which in turn can pass it to controller methods. As shown here (Socket.io emit from Express controllers)

However, I have a controller method that needs to emit progress to any client who happens to be listening, but this method can be executed from many different routes, and other controllers, and I don't really want to have to pass a reference to socket around all these other parts of the app.

Is there a better way to do it?

I was thinking something like a socketio helper module. The app.js module passes it a reference to io, which can be retrieved later....

app.js

var io = require('socket.io').listen(server);    
require('./helpers/socketio').set(io);

helpers/socketio.js

var io=null;

exports.set = function(socketio) {
   io=socketio;
}

exports.get = function() {
  return io;
}

Then whenever you need it in the app..

var io = require('./helpers/socketio').get();
io.emit('message', {a:1, b:2});

Is there a cleaner way to do this? Clearly it could return null, which you would have to check for. It just doesn't feel right....

解决方案

Modules are cached after the first time they are loaded.

Actually, you can verify socket.io at helper/socketio.js. Although you call require() that socketio.js from other files, node.js will execute code on that file only one time.

You can look Node Documentation

这篇关于Socket io从express controller方法向客户端发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆