获取路由请求中的套接字 ID



如何在路由请求中获取客户端的套接字 ID。

例如

io.on('connection',function(socket)
{
var socketId = socket.id;
}
router.get('/',function(req, res){
{
let socket = io.sockets.sockets[socketId];
// How can I get the socketId of the client sending this request
}

当我将socketId声明为全局变量时,当多个用户使用该应用程序时,它不起作用。

如果为此提出解决方案,将会有所帮助。提前致谢

您可以在握手期间添加 id 作为查询字符串,将此 id 存储在服务器上,并让客户端每次将此 id 发送到服务器进行身份验证。例如:

client.js

const clientId = "some_unique_id";
const socket = io('http://localhost?id=' + clientId);
fetch('http://localhost?some_key=some_value&id=' + clientId).then(/*...*/);

server.js

const io = require('socket.io')();
// this should be a database or a cache
const idToConnectionHash = {};
io.on('connection', (socket) => {
let id = socket.handshake.query.id;
idToConnectionHash[id] = socket.id;
// ...
});
router.get('/',function(req, res){
let socket = idToConnectionHash[req.query.id];
// ...
}

最新更新