在express +socket.io+session 如何在socket.io里面获取session!求赐教
发布于 2年前 作者 ljy0662 3984 次浏览
9 回复
  1. server.js
//session & cookie
var sessionStore = new express.session.MemoryStore({reapInterval: 60000 * 10});
app.use(express.cookieParser());
app.use(express.session({
  store: sessionStore,
  key: 'sid',
  secret: config['session_secret']
}));

//start http server && socket.io
var server = http.createServer(app);
var io = require('socket.io').listen(server,{
  'log level': 2,
  'browser client minification': true
});
var chatServer = require('./controllers/chat').init(io, app, sessionStore);

2. chat.js

/**
 * 初始化ChatServer
 */
exports.init = function(io, app, sessionStore){
  var chatServer = io.of('/chat');
  var userList = {};

  chatServer.authorization(function (handshakeData, callback) {
      //没有cookie则退出
      if (!handshakeData.headers.cookie) return callback('socket.io: no found cookie.', false);

      //根据cookie找sessionId,https://github.com/DanielBaulig/sioe-demo/blob/master/app.js
      var signedCookies = require('express/node_modules/cookie').parse(handshakeData.headers.cookie);
      handshakeData.cookies = require('express/node_modules/connect/lib/utils').parseSignedCookies(signedCookies,
      app.get('config')['session_secret']);

      //根据sessionId找username
      sessionStore.get(handshakeData.cookies['sid'], function(err,session){
        if(err || !session) return callback('socket.io: no found session.', false);
        handshakeData.session = session;
        if(handshakeData.session.user){ 
          return callback(null, true);
        }else{
          return callback('socket.io: no found session.user', false);
        }
      })
  });

呵呵,我也同样的问题,几乎同样的代码,求大神。表示写rails的自学node.js很有压力

额,2了,原来有回复。。。把大神当提问人了额。。。

这个适用express3.0

赞! 不过有个细节不太一样

var signedCookies = express_cookie.parse(handshakeData.headers.cookie);

handshakeData.cookies = parseCookie(signedCookies[‘connect.sid’],settings[‘cookie_secret’]);

sessionStore.get(handshakeData.cookies, function(err,session){

cookie parse出来是个对象,所以要变成signedCookies[‘connect.sid’],handshakeData.cookies并且不会直接有sid这个key

p.s 引用路径换掉了,清楚些

使用session.socket.io这个模块.

回到顶部