我有这两个文件:
io.js:
var io = require('socket.io')();
var socketioJwt = require('socketio-jwt');
var jwtSecret = require('./settings').jwtSecret;
io.set('authorization', socketioJwt.authorize({
secret: jwtSecret,
handshake: true
}));
io.on('connection', function(socket) {
IO.pushSocket(socket);
});
var IO = module.exports = {
io: io,
sockets: [],
pushSocket: function(socket) {
if (typeof IO.sockets === 'undefined') {
IO.sockets = [];
}
IO.sockets.push(socket);
console.log(IO.sockets);
}
}
main.js:
var sockets = require('./io').sockets;
console.log(sockets); \\ output is []
您可能会注意到,在用户连接时,我正在尝试推送到IO模块中的套接字阵列。但是当我在main.js中记录数组时,它总是以空数组的形式返回。任何的想法 ?
谢谢。
答案 0 :(得分:0)
您在代码(require('./io').sockets
)实际创建数组之前获取pushSocket()
。
在数组存在之前无法读取它。
您可能希望立即创建数组,因此在您尝试阅读之前它将存在。
答案 1 :(得分:0)
我建议采用一种不同的解决方案。你根本不需要跟踪你自己的连接套接字数组,因为socket.io已经为你做了。它提供了一个套接字数组和一个套接字映射(由socket id索引):
// io.js
var io = require('socket.io')();
var socketioJwt = require('socketio-jwt');
var jwtSecret = require('./settings').jwtSecret;
io.set('authorization', socketioJwt.authorize({
secret: jwtSecret,
handshake: true
}));
io.on('connection', function(socket) {
// whatever you want to do here
});
module.exports = io;
然后,要使用该模块,您可以这样做:
// main.js:
var io = require('./io');
// then sometime later AFTER some sockets have connected
console.log(io.sockets.sockets); // array of connected sockets
以下是您可以在io
对象中使用的一些数据结构:
io.sockets.sockets // array of connected sockets
io.sockets.connected // map of connected sockets, with socket.id as key
io.nsps // map of namespaces in use
io.nsps['/'].sockets // array of connected sockets in the "/" namespace (which is the default)
io.nsps['/'].connected // map of connected sockets in the "/" namespace
如果您想跟踪io模块外部的连接和断开事件,您可以直接订阅connection
和disconnect
事件,而无需为其创建自己的方案:
// main.js:
var io = require('./io');
io.on('connection', function(socket) {
// new socket just connected
console.log(io.sockets.sockets); // array of connected sockets
socket.on('disconnect', function() {
// socket just disconnected
});
});