Friday, 7 April 2017

Is it possible to keep an id for WebSocket in js

I'm trying to create dialogue system using WebSockets on both Client and Server side. My goal is to keep list of connections so I can iterate through them fast and get ws value just by it's user id.
I was planning to save WebSocket in array where key is id of it's owner but i don't know if I can save additional info in webSocket instance and if user can read or change data from it?
What's the safest and fastest way to save data?

My current code is:

const WebSocketServer = require('ws').Server;  
   var wss = new WebSocketServer({
   server: httpsServer
});

connected = [];
count = 0;
wss.on('connection', function(ws) {
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
        data = JSON.parse(message);
        type=data[0];
        if(type == 0){
            connected[data[1][0]] = ws;
            ws.id = data[1][0];
            console.log(ws.id);
        } else if (type == 1){
            toUser = connected[data[1][0]];
            toUser.send(data[1][1]);
        }
    });
    ws.on('close', function (ws) {
            console.log(ws.id);
            connected.slice(ws.id, 1);
    });
});

I do understand that I don't change the ws variable when I get a message cause log in close get me undefined but it is how I think it should work.



via 0shn1x