简体   繁体   中英

How do I remove a WebSocket object from a JavaScript array?

I am currently adding a WebSocket client object to an array so I can match it (by index) to another array of user information, to determine which user belongs to which client/socket/session.

var users = [];
var clients = [];
...
wss.on('connection', function connection(ws) {

    clients.push(ws);
    var i = clients.indexOf(ws);
    if(i > -1) {
        users.push({
        id: i,
        user: "",
        room: "",
        client: clients[i],
    }); 
    }

    ws.on('close', function(ws) {
        var i = clients.indexOf(ws); //i = -1
        if(i > -1) { 
            // remove this client and user...
        }
    });

    ws.on('message', function incoming(message) {
      // do stuff
    });
});

I am able to get the index of the ws object (which returns 0) so I am able to insert the object as part of the JSON object to the "users" array fine. But when I attempt to remove the same ws object when the connection is closed -1 is returned for indexOf(ws) . But surely it should return 0 as it is the same object(connection) as previously used and is still present at index 0 in the clients array?

Why is indexOf() returning -1 in the "close" handler?

The close event listener does not get a WebSocket as its first argument, if you're using the ws module in Node. The docs say the first argument is closing code reason , not a socket.

Instead, you already have the socket in the outer ws variable. Don't shadow it with an argument named ws , and your code should work fine:

ws.on('close', function(code, message) {
    var i = clients.indexOf(ws);
    //...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM