我在从辅助文件访问套接字时遇到问题:
有两个文件:
1)main.js
2)secondary.js
在main.js中:
var sec = require('./secondary.js');
function DoFuncOnSecondaryFile(){
setInterval(function(){
//here i can't pass the socket, because it is not inside "io.on connection"
sec.myExternalFunc( socket );
}, 5000);
}
io.on('connection', function(socket){
//all the socket events in here
});
在secondary.js中:
module.exports = {
myExternalFunc: function(){
socket.emit("message", "I cannot reach the socket so i will throw an error");
socket.to(anId).emit("message", "Supposing 'anId' is correctly defined and it is the id of a connected socket, this function won't work anyway!");
}
}
我需要函数" myExternalFunc()"每隔5秒执行一次,如果我想将套接字作为参数传递,我需要将它放在io.on(' connection')中,以便定义套接字变量,但是我的Interval将启动每当有人连接。 如何在外部文件中使用emit,我无法传递套接字变量?