简体   繁体   English

socket.io-TypeError:无法读取未定义的属性“握手”

[英]socket.io - TypeError: Cannot read property 'handshaken' of undefined

I'm getting the error "TypeError: Cannot read property 'handshaken' of undefined" when using my app since I've installed socket.io 由于安装了socket.io,使用我的应用程序时出现错误“ TypeError:无法读取未定义的属性'握手'”

It seems that the checkUserHaveConnect method within the helpers/utils.js file is causing the error as my console.log("io 2", io") is called just before the error (this can be seen in my screenshot below) 似乎helpers/utils.js文件中的checkUserHaveConnect方法导致了错误,因为我的console.log(“ io 2”,io“)在错误之前被调用(可以在下面的屏幕截图中看到)

The strange thing is, that this error does not occur on my development environment (laptop), but only when deployed in production (nodejitsu). 奇怪的是,此错误不会在我的开发环境(笔记本电脑)上发生,而只会在部署到生产环境(nodejitsu)时发生。

Firstly, here is my index file where the socket.io connection is initiated. 首先,这是我的索引文件,其中启动了socket.io连接。

index.js index.js

var server = http.createServer(app);

var io = require('socket.io').listen(server);
GLOBAL.io = io;

// launch
server.listen(port);

//With Socket.io >= 1.0
io.use(passportSocketIo.authorize({
    cookieParser: express.cookieParser,
    key:         EXPRESS_SID_KEY,       // the name of the cookie where express/connect stores its session_id
    secret:      SESSION_SECRET,    // the session_secret to parse the cookie
    store:       sessionStore,        // we NEED to use a sessionstore. no memorystore please
    success:     onAuthorizeSuccess,  // *optional* callback on success - read more below
    fail:        onAuthorizeFail,     // *optional* callback on fail/error - read more below
}));

io.on('connection', function (socket) {
    console.log("connection come");

    socket.on('disconnect', function (socket) {
        console.log("disconnect come");
    });
});

function onAuthorizeSuccess(data, accept){
    console.log('successful connection to socket.io');
    accept(null, true);
}

function onAuthorizeFail(data, message, error, accept){
    console.log('failed connection to socket.io:', message);
    if(error){
        throw new Error(message);
    }
    // We use this callback to log all of our failed connections.
    accept(null, false);
}

console.log('The magic happens on port' + port);

Here are the methods where the problem might be caused. 这里是可能导致问题的方法。

helpers/utils.js 助手/ utils.js

var passportSocketIo = require("passport.socketio");
exports.emitData = function(userId, eventName,data){

console.log("io 1", io);

    var sockets = passportSocketIo.filterSocketsByUser(io, function(user){
        if(user._id){
            return user._id.toHexString() === userId.toHexString();
        }
        return false;
    });
    sockets.forEach(function(socket){
        socket.emit(eventName,data);
    });
    return sockets.length;
}

exports.checkUserHaveConnect = function(userId){

console.log("io 2", io);

    return passportSocketIo.filterSocketsByUser(io, function(user){
        if(user._id){
            return user._id.toHexString() === userId.toHexString();
        }
        return false;
    }).length;
}

错误

The feature is broken because socket.io > 1.0 has no more handshake data (replaced by "request"), which is used in the passport.socketio filterSocketsByUser method. 该功能已损坏,因为socket.io> 1.0不再有握手数据(由“ request”代替),该数据在password.socketio filterSocketsByUser方法中使用。

There is a fix on the way to the npm, in the meantime, you can replace in the package : 到npm的途中有一个修复,与此同时,您可以在软件包中进行替换:

function filterSocketsByUser(socketIo, filter){
  var handshaken = socketIo.sockets.manager.handshaken;
  return Object.keys(handshaken || {})
    .filter(function(skey){
      return filter(handshaken[skey].user);
    })
    .map(function(skey){
      return socketIo.sockets.manager.sockets.sockets[skey];
    });
}

by the following (courtesy of Gausie ) : 通过以下方式(由高斯提供 ):

function filterSocketsByUser(socketIo, filter){
  var handshaken = [];
  for ( var i in socketIo.sockets.connected )
    if ( socketIo.sockets.connected[i].handshake )
        handshaken.push( socketIo.sockets.connected[i] )

  return Object.keys(handshaken || {})
    .filter(function(skey){
      return filter(handshaken[skey].conn.request.user);
    })
    .map(function(skey){
      return handshaken[skey];
    });
}

Source : Github 资料来源: Github

To fix this I had to use the latest version of passport.socketio as the version on NPM is out of date. 要解决此问题,我必须使用passport.socketio的最新版本,因为NPM上的版本已过时。

As I'm using nodejitsu, I had to add a "bundleDependencies" section in the package.json file like this: 当我使用nodejitsu时,我必须在package.json文件中添加一个“ bundleDependencies”部分,如下所示:

"bundleDependencies": [
"passport.socketio"
],

This ensures that my local version of passport.socketio is used rather than the NPM version. 这样可以确保使用本地版本的passport.socketio,而不是NPM版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Socket.io TypeError:无法读取未定义的属性“hteam” - Socket.io TypeError: Cannot read property 'hteam' of undefined Socket.io - UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'emit' of undefined - Socket.io - UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'emit' of undefined Socket.IO TypeError:无法读取未定义的属性“广播” - Socket.IO TypeError: Cannot read property 'broadcast' of undefined Socket.IO TypeError:无法读取未定义的属性“发出” - Socket.IO TypeError: Cannot read property 'emit' of undefined Socket.io引发“ TypeError:无法读取未定义的属性'push'” - Socket.io raises “TypeError: Cannot read property 'push' of undefined” Angular2 CLI Socket.io无法读取未定义的属性“ on” - Angular2 CLI Socket.io Cannot read property 'on' undefined AngularJS Socket.io:无法读取未定义的属性“ emit” - AngularJS Socket.io: Cannot read property 'emit' of undefined Karma无法读取未定义的socket.io的属性'prototype'? - Karma Cannot read property 'prototype' of undefined socket.io? Socket.io:“无法读取未定义的属性'emit'” - Socket.io : “Cannot read property 'emit' of undefined” Node.js和Socket.io-无法读取未定义的属性“ on” - Node.js & Socket.io - Cannot read property 'on' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM