【问题标题】:Retrieving socket.io connection that pertains to HTTP request检索与 HTTP 请求相关的 socket.io 连接
【发布时间】:2015-09-08 11:39:43
【问题描述】:

我正在使用带有 Express 的 socket.io。

假设用户点击了规范路由 /,请求被路由到:

app.get('/',function(req,res,next){

   var msg =...;
   socket.emit('channel',msg); //how do I find the right socket object that pertains to this HTTP request?

});

使用 socket.io 找到与此 HTTP 请求相关的套接字连接的最佳方法是什么?

我最好的猜测是在套接字连接被验证时用会话 id 标记套接字,然后稍后用相同的会话 id 检索它们(在上面的函数中)?会话 ID 在 Express 中间件中的请求对象上可用。

我还有这个代码将 socket.io 绑定到 Express 服务器:

var server = http.createServer(app).listen(port);
var io = require('socket.io').listen(server);  //we need to bind socket.io to the http server

还有我自己的socketio模块,我这样做:

var cookie = require("cookie");
var connect = require("connect");

var io = null;
var connectedUsers = {}; //hash of sockets with socket.id as key and socket as value

var init = function ($io) {

    if (io === null) {

        io = $io;

        io.use(function (socket, next) {
            var handshakeData = socket.request;

            if (handshakeData.headers.cookie && handshakeData.cookie) {

                handshakeData.cookie = cookie.parse(handshakeData.headers.cookie);

                //handshakeData.sessionID = connect.utils.parseSignedCookie(handshakeData.cookie['express.sid'], 'foo'); //pass session secret at end

                handshakeData.sessionID = cookie.parse(handshakeData.cookie['express.sid'], 'foo'); //pass session secret at end

                if (handshakeData.cookie['express.sid'] == handshakeData.sessionID) {
                    return next('Cookie is invalid.', false);
                }

            } else {
                return next('No cookie transmitted.', false);
            }

            console.log('user with socket.id=', socket.id, 'has authenticated successfully.');
            return next(null, true);

        });


        io.on('connection', function (socket) {
            console.log('a user connected - ', socket.id);

            connectedUsers[socket.id] = socket;

            socket.on('chat message', function (msg) {
                console.log(socket.id, 'says', msg);

                socket.emit('chat message', 'hey baby hey - I am '.concat(socket.id));
            });

            socket.on('disconnect', function () {
                console.log('user disconnected -', socket.id);
                connectedUsers[socket.id] = null;
            });
        });
    }
    else if ($io != null) {
        throw new Error('tried to re-init socketio.js by passing new value for io in?? what are you doing.')

    }
    else {

    }


    return {

        addListener: function(){

    }


};

module.exports = init;

【问题讨论】:

    标签: node.js sockets express socket.io


    【解决方案1】:

    您必须创建一个数组或 json 对象并在连接到服务器时保存套接字对象。就像这样:

    var clients = {}
    io.on("connection", function(socket){
       socket.on("login", function(data){
           clients[data.user] = socket;
       });
    });
    

    然后,当您收到 https 请求时,客户端将用户作为参数传递,然后您查看对象客户端:

    clients[user].emit(...)
    

    【讨论】:

      猜你喜欢
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      • 2022-09-23
      • 2012-02-06
      • 2017-04-30
      • 1970-01-01
      相关资源
      最近更新 更多