[英]NodeJS, websocket, and module.export
I have a server.js file. 我有一个server.js文件。
Inside, i defined my routes. 在里面,我定义了我的路线。
// routes
var mainRoutes = require('./routes/main.js')(app, express);
var apiRoutes = require('./routes/api.js')(app, express);
var socketRoutes = require('./routes/socket.js');
app.use('/', mainRoutes);
app.use('/api', apiRoutes);
// socket.io communication
io.sockets.on('connection', socketRoutes);
My socket.js file looks like that : 我的socket.js文件如下所示:
module.exports = function (socket) {
console.log('user connected');
socket.on('myEvent', function(data) {
// whatever ...
});
}
Inside this function, i can catch events and send some. 在此功能内,我可以捕获事件并发送一些事件。 BUT i need to send a message to everyone at some point. 但是我需要在某个时候向所有人发送消息。 Let say when i receive an 'myEvent' event. 假设我收到“ myEvent”事件。
So basically, i would like to do : 所以基本上,我想做:
io.sockets.emit('messageForEveryone', "This is a test");
But here, i can only work on the 'socket' argument, which is for 1 person only i guess. 但是在这里,我只能处理'socket'参数,我猜这仅适用于1个人。
I would like to pass io from server.js, to socket.js. 我想将io从server.js传递到socket.js。
I tried that (in server.js) : 我尝试了(在server.js中):
var socketRoutes = require('./routes/socket.js', io);
And that (in socket.js) : 那(在socket.js中):
module.exports = function (io, socket)
Obviously, it's not working. 显然,它不起作用。 I don't even understand where the socket argument is coming from. 我什至不知道套接字参数从何而来。
Question : How can i work on io object, when i'm inside the module.export of the sockets.js file ? 问题:当我在sockets.js文件的module.export中时,如何处理io对象?
I would really appreciate any help, i'm new to all of this. 我真的很感谢您的帮助,我是这一切的新手。
Thanks ! 谢谢 !
Since you just want to emit to all clients, instead of passing io
to socketRoutes
, you can simply do this. 由于您只想向所有客户端发出消息,而不是将io
传递给socketRoutes
,因此只需执行此操作。
module.exports = function (socket) {
var sockets = this;
console.log('user connected');
socket.on('myEvent', function(data) {
sockets.emit('hello_all_clients',data);
});
}
You could return a function from exports as such. 您可以这样从导出返回函数。
module.exports = function (io) { // pass io to initialize
return function (socket) {
// io and socket are both scoped
}
}
then in server.js 然后在server.js中
// socket.io communication
io.sockets.on('connection', socketRoutes(io));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.