在路由请求中获取socketId

时间:2018-10-12 07:12:33

标签: node.js socket.io mean-stack

如何在路由请求中获取客户端的套接字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声明为全局变量时,当多个用户使用该应用程序时,它不起作用。

如果为此提出了解决方案,将有帮助。预先感谢

1 个答案:

答案 0 :(得分:0)

您可以在握手期间添加一个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];
  // ...
}
相关问题