我正在使用socket.io制作一款聊天应用程序,我想使用自定义客户端ID而不是默认的ID (8411473621394412707
, 1120516437992682114
)。是否有任何方法可以在连接时发送自定义标识符,或者只是使用某些内容来跟踪每个ID的自定义名称?谢谢!
我正在使用socket.io制作一款聊天应用程序,我想使用自定义客户端ID而不是默认的ID (8411473621394412707
, 1120516437992682114
)。是否有任何方法可以在连接时发送自定义标识符,或者只是使用某些内容来跟踪每个ID的自定义名称?谢谢!
你可以在服务器上创建一个数组,并将自定义对象存储在其中。例如,你可以将Socket.io创建的ID和每个客户端发送到服务器的自定义ID存储在其中:
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函数。
<script>
var socket = io.connect('http://localhost', {port: 8080});
socket.on('connect', function (data) {
socket.emit('storeClientInfo', { customId:"000CustomIdHere0000" });
});
</script>
希望这可以帮到你。
要设置自定义的socket id,必须覆盖generateId函数。可以使用Socket.io
服务器对象的eio
和engine
属性来管理此操作。
一个简单的例子:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.engine.generateId = function (req) {
// generate a new custom id here
return 1
}
io.on('connection', function (socket) {
console.log(socket.id); // writes 1 on the console
})
看起来它已经被处理了。
必须记住,套接字ID必须是不可预测的和唯一的值,同时考虑安全性和应用程序操作!
额外内容:如果因为您在generateId
方法上的强烈进程而返回undefined
作为socket.id
,则可以使用async/await
组合来解决此问题,在node.js
7.6.0及更高版本中, 应更改node_modules/engine.io/lib/server.js
文件的handshake
方法如下:
当前内容:
// engine.io/lib/server.js
Server.prototype.generateId = function (req) {
return base64id.generateId();
};
Server.prototype.handshake = function (transportName, req) {
var id = this.generateId(req);
...
}
新:
// function assignment
io.engine.generateId = function (req) {
return new Promise(function (resolve, reject) {
let id;
// some intense id generation processes
// ...
resolve(id);
});
};
// engine.io/lib/server.js
Server.prototype.handshake = async function (transportName, req) {
var id = await this.generateId(req);
...
}
注意:在Engine.io v4.0中,generateId
方法将接受一个回调函数。因此,不需要更改handshake
方法,仅替换generateId
方法就足够了。例如:
io.engine.generateId = function (req, callback) {
// some intense id generation processes
// ...
callback(id);
};
{ query: { foo: 'foo' } }
。然后在服务器上,你必须通过解析 req.url
来获取它,就像这里描述的那样:https://nodejs.org/api/url.html#url_constructor_new_url_input_base,像这样:const parsedUrl = new url.URL(req.url, host)
。一旦你解析了 URL,你就可以像这样访问查询参数:parsedUrl.searchParams.get('foo')
。如果你有一个 stack overflow 的问题,请提供链接,这样解释起来会更容易。 - Daniel Reinasocket = io.connect('http://localhost');
socket.on('connect', function() {
console.log(socket.io.engine.id); // old ID
socket.io.engine.id = 'new ID';
console.log(socket.io.engine.id); // new ID
});
这将适用于2.2.0版本及以上的Socket.IO
要设置自定义Socket Id,必须覆盖generateId
函数。
一个简单的示例:
服务器端
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.use((socket, next) => {
io.engine.generateId = () => {
// USE ONE OF THESE
socket.handshake.query.CustomId; // this work for me
// return socket.handshake.query.CustomId;
}
next(null, true);
});
io.on('connection', function (socket) {
console.log(socket.id);
})
客户端
io.connect(URL, { query: "CustomId = CUSTOM ID IS HERE" })
注意:请记住,套接字 ID 必须是唯一的值。
我会使用对象作为哈希查找 - 这样可以避免循环数组的操作
var clients = {};
clients[customId] = clientId;
var lookup = clients[customId];
io.on("connection", (socket) => {
socket.on('storeClientInfo', (data) => {
console.log("connected custom id:", data.customId);
socket.customId = data.customId;
});
socket.on("disconnect", () => {
console.log("disconnected custom id:", socket.customId);
})
});
客户端
let customId = "your_custom_device_id";
socket.on("connect", () => {
socket.emit('storeClientInfo', { customId: customId });
});
或者您可以覆盖套接字ID,像这样:
io.on('connection', function(socket){
socket.id = "YOUR_CUSTOM_ID";
});
io.sockets.connected[socketid]
这样的情况下,套接字仍然被其原始id引用。 - RossBilleio.use((socket, next) => {
io.engine.generateId = () => socket.handshake.query.token;
next(null, true);
});
var userId_SocketId_KeyPair = {};
var socketId_UserId_KeyPair = {};
_io.on('connection', (socket) => {
console.log('Client connected');
//On socket disconnect
socket.on('disconnect', () => {
// Removing sockets
let socketId = socket.id;
let userId = socketId_UserId_KeyPair[socketId];
delete socketId_UserId_KeyPair[socketId];
if (userId != undefined) {
delete userId_SocketId_KeyPair[userId];
}
console.log("onDisconnect deleted socket with userId :" + "\nUserId,socketId :" + userId + "," + socketId);
});
//Store client info
socket.on('storeClientInfo', function (data) {
let jsonObject = JSON.parse(data);
let userId = jsonObject.userId;
let socketId = socket.id;
userId_SocketId_KeyPair[userId] = socketId;
socketId_UserId_KeyPair[socketId] = userId;
console.log("storeClientInfo called with :" + data + "\nUserId,socketId :" + userId + "," + socketId);
});
`