【问题标题】:Getting the socketId in the route request获取路由请求中的socketId
【发布时间】:2018-10-12 07:12:32
【问题描述】:

如何在路由请求中获取客户端的套接字 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 相关联,并在套接字首次连接时将其发送到前端。用户可以在发出获取请求时提供该哈希

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2017-05-14
    • 1970-01-01
    • 2016-09-09
    • 2015-07-22
    • 1970-01-01
    • 2020-09-25
    相关资源
    最近更新 更多