Unable to persist a sockets array upon user connection

两盒软妹~` 提交于 2019-12-08 10:02:56

问题


I have these two files:

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 []

As you may notice, upon user connection I am trying to push to the sockets array in the IO module. But when I log the array in main.js it always returns as empty array. Any idea ?

Thank you.


回答1:


You're fetching require('./io').sockets before the code (in pushSocket()) actually creates the array.

You cannot read an array before it exists.

You probably want to create the array immediately, so it will exist before you try to read it.




回答2:


I'd suggest a bit of a different solution. You don't need to keep track of your own array of connected sockets at all because socket.io already does that for you. It provides both an array of sockets and a map of sockets (indexed by 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;

Then, to use that module, you can do this:

// main.js:
var io = require('./io');


// then sometime later AFTER some sockets have connected
console.log(io.sockets.sockets);        // array of connected sockets

Here are some of the data structures you can use from the io object:

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

If you want to then track connect and disconnect events from outside the io module, you can just directly subscribe to the connection and disconnect events without having to invent your own scheme for it:

// 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
    });
});


来源:https://stackoverflow.com/questions/39196031/unable-to-persist-a-sockets-array-upon-user-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!