生成套接字ID时,使用自定义名称修改socket.name

时间:2016-01-08 15:20:50

标签: node.js express socket.io

我只是尝试将自定义数据从客户端发送到服务器,而不添加更多请求。

我正在阅读帖子:socket.io socket.set and socket.get - what is the callback argument for? 并说:The get and set functions on the socket object were removed in version 1.x

我使用非常简单的节点/快速应用程序,使用下一个代码:

var io = require('socket.io').listen(http);
io.on('connection', function(socket){
    console.log('a user connected: ' + socket.id);
    socket.on('disconnect', function(){
        console.log( socket.name + ' has disconnected from the chat.' + socket.id);
    });
});

在套接字初始化时,是否存在在属性socket.name中设置自定义值的方法?

1 个答案:

答案 0 :(得分:0)

只有当您不需要将您的应用程序放在群集中或在其他服务器上运行时,此解决方案才有效。

var clients = {};

io.on('connection', function(socket){
    console.log('a user connected: ' + socket.id);

    clients[socket.id] = {name: 'Your name'};

    socket.on('disconnect', function(){
        console.log( clients[socket.id].name + ' has disconnected from the chat.' + socket.id);
        delete clients[socket.id]; //Delete client
    });
});

之后,您可以通过这种方式找到相关数据:

clients[socket.id];