9 回复
- 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); } }) });
赞! 不过有个细节不太一样
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 引用路径换掉了,清楚些