获取路由请求中的socketId

Getting the socketId in the route request

如何在路由请求中获取客户端的套接字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作为query string,将这个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];
  // ...
}