生成socket ID时用自定义名称修改socket.name
Modify socket.name with a custom name when the socket ID is generated
我只是想将自定义数据从客户端发送到服务器,而不添加更多请求。
我正在阅读线程: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.
我正在使用一个非常简单的 node/express 应用程序,下一个代码:
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
中设置自定义值的方法?
此解决方案仅适用于您不需要在集群中或 运行 在其他服务器中的应用程序。
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];
我只是想将自定义数据从客户端发送到服务器,而不添加更多请求。
我正在阅读线程: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.
我正在使用一个非常简单的 node/express 应用程序,下一个代码:
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
中设置自定义值的方法?
此解决方案仅适用于您不需要在集群中或 运行 在其他服务器中的应用程序。
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];