How to store client associated data in socket.io 1.0

后端 未结 2 549
眼角桃花
眼角桃花 2021-02-07 05:15

The docs say socket.io doesn\'t support .get .set now

Is it okay to store client associated data like

io.sockets.on(\'connection\', function (client) {
         


        
2条回答
  •  不要未来只要你来
    2021-02-07 05:56

    Yes, that's possible as long as there is no other builtin properties with same name.

    io.sockets.on('connection', function (client) {
        client.on('data', function (somedata) {  
            // if not client['data']  you might need to have a check here like this
            client['data'] = somedata;
        });    
    });
    

    I'd suggest another way, but with ECMAScript 6 weak maps

    var wm = new WeakMap();
    
    io.sockets.on('connection', function (client) {
        client.on('data', function (somedata) {   
            wm.set(client, somedata);
            // if you want to get the data
            // wm.get(client);
        }); 
        client.on('disconnect', function() {
            wm.delete(client);
        });   
    });
    

提交回复
热议问题