How do I remove a WebSocket object from a JavaScript array? -
i adding websocket client object array can match (by index) array of user information, determine user belongs client/socket/session.
var users = []; var clients = []; ... wss.on('connection', function connection(ws) { clients.push(ws); var = clients.indexof(ws); if(i > -1) { users.push({ id: i, user: "", room: "", client: clients[i], }); } ws.on('close', function(ws) { var = clients.indexof(ws); //i = -1 if(i > -1) { // remove client , user... } }); ws.on('message', function incoming(message) { // stuff }); });
i able index of ws
object (which returns 0) able insert object part of json object "users" array fine. when attempt remove same ws
object when connection closed -1
returned indexof(ws)
. surely should return 0
same object(connection) used , still present @ index 0 in clients array?
why indexof() returning -1 in "close" handler?
the close
event listener not websocket
first argument, if you're using ws
module in node. docs first argument closing code
reason, not socket.
instead, have socket in outer ws
variable. don't shadow argument named ws
, , code should work fine:
ws.on('close', function(code, message) { var = clients.indexof(ws); //... });
Comments
Post a Comment