Socket.io自定义客户端ID [英] Socket.io custom client ID
问题描述
我正在使用socket.io创建一个聊天应用,我想使用我的自定义客户端ID,而不是默认值( 8411473621394412707
, 1120516437992682114
)。在连接或仅使用某些内容跟踪每个ID的自定义名称时,是否有任何方法可以发送自定义标识符?谢谢!
I'm making a chat app with socket.io, and I'd like to use my custom client id, instead of the default ones (8411473621394412707
, 1120516437992682114
). Is there any ways of sending the custom identifier when connecting or just using something to track a custom name for each ID? Thanks!
推荐答案
您可以在服务器上创建一个数组,并在其上存储自定义对象。例如,您可以将Socket.io创建的ID和每个客户端发送的自定义ID存储到服务器:
You can create an array on the server, and store custom objects on it. For example, you could store the id created by Socket.io and a custom ID sent by each client to the server:
var util = require("util"),
io = require('/socket.io').listen(8080),
fs = require('fs'),
os = require('os'),
url = require('url');
var clients =[];
io.sockets.on('connection', function (socket) {
socket.on('storeClientInfo', function (data) {
var clientInfo = new Object();
clientInfo.customId = data.customId;
clientInfo.clientId = socket.id;
clients.push(clientInfo);
});
socket.on('disconnect', function (data) {
for( var i=0, len=clients.length; i<len; ++i ){
var c = clients[i];
if(c.clientId == socket.id){
clients.splice(i,1);
break;
}
}
});
});
在此示例中,您需要从每个客户端调用 storeClientInfo 。 / p>
in this example, you need to call storeClientInfo from each client.
<script>
var socket = io.connect('http://localhost', {port: 8080});
socket.on('connect', function (data) {
socket.emit('storeClientInfo', { customId:"000CustomIdHere0000" });
});
</script>
希望这有帮助。
这篇关于Socket.io自定义客户端ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!