How to store client associated data in socket.io 1.0

狂风中的少年 提交于 2020-12-29 02:53:45

问题


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) {
    client.on('data', function (somedata) {            
        client['data'] = somedata;
    });    
});

in case I need multiple nodes?


回答1:


Yes, it is OK to add properties to the socket.io socket object. You should be careful to not use names that could conflict with built-in properties or methods (I'd suggest adding a leading underscore or namescoping them with some sort of name prefix). But a socket is just a Javascript object and you're free to add properties like this to it as long as you don't cause any conflict with existing properties.

There are other ways to do this that use the socket.id as a key into your own data structure.

var currentConnections = {};
io.sockets.on('connection', function (client) {
    currentConnections[client.id] = {socket: client};
    client.on('data', function (somedata) {  
        currentConnections[client.id].data = someData; 
    });    
    client.on('disconnect', function() {
        delete currentConnections[client.id];
    });
});



回答2:


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


来源:https://stackoverflow.com/questions/29933957/how-to-store-client-associated-data-in-socket-io-1-0

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