使用最新版本的connect(截至2012-07-26),我发现以下方法可以从socket.io获取可与connect-redis商店一起使用的会话ID。
var express = require('express')
, routes = require('./routes')
, fs = require('fs')
, http = require('http')
, io = require('socket.io')
, redis = require('connect-redis')
, connect = require('express/node_modules/connect')
, parseSignedCookie = connect.utils.parseSignedCookie
, cookie = require('express/node_modules/cookie');
var secret = '...';
var rStore = new(require('connect-redis')(express));
//...
var server = http.createServer(app);
var sio = io.listen(server);
sio.set('authorization', function(data, accept) {
if(data.headers.cookie) {
data.cookie = cookie.parse(data.headers.cookie);
data.sessionID = parseSignedCookie(data.cookie['connect.sid'], secret);
} else {
return accept('No cookie transmitted', false);
}
accept(null, true);
});
然后可以稍后使用 data.sessionID
,例如
sio.sockets.on('connection', function(socket) {
console.log('New socket connection with ID: ' + socket.handshake.sessionID);
rStore.get(socket.handshake.sessionID, function(err, session) {
//...
});
});
从express(连接,连接实用程序和cookie模块)导入这么多内容似乎是一种过于迂回的方式来获取解析connect的签名cookie所需的功能。有没有人找到另一种方式?