How to store client associated data in socket.io 1.0

后端 未结 2 517
眼角桃花
眼角桃花 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:45

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

提交回复
热议问题