如何将express 4中的会话与socket.io联系起来,以便可以在两个方向上检索和保存会话数据?
socket.io中的身份验证基于令牌,jwt
在多个虚拟主机中共享相同的套接字
例如:
global.socket.of('/secure').on('connection', function(socket){
console.log('client connected to "secure" socket');
});
app.js
var port = 3000,
jwtSecret = '26fed98d8c6c7c54f485f1ee7ffe44d2e1feae28';
var app = require('express')(),
vhost = require('vhost'),
server = require('http').createServer(app),
socketioJwt = require('socketio-jwt');
// Start server with socket.io
global.socket = require('socket.io').listen(app.listen(port, function(){
console.log('Express server listening on port '+port);
}));
// Socket authentication
global.socket.set('authorization', socketioJwt.authorize({
secret: jwtSecret,
handshake: true
}));
// Virtual hosts
app.use(vhost('secure.domain.com', require('./vhost/secure')(jwtSecret)));
虚拟主机/ secure.js
var express = require('express'),
http = require('http'),
jwt = require('jsonwebtoken');
function Host(jwtSecret){
var app = express();
// Session
app.use(require('cookie-parser')());
app.use(require('express-session')({
secret: '0a6e0caf5477cee686726ad06284309eb4a580e4',
key: 'express.sid',
cookie: {
maxAge : 1000*60*10
}
}));
// HTTP 200
app.get('/', function(req, res){
res.end('helle world!');
});
app.post('/login', function(req, res){
var profile = {
id: 1,
name: 'username'
};
var token = jwt.sign(profile, jwtSecret, {expiresInMinutes: 60});
res.json({token: token});
});
global.socket.of('/secure').on('connection', function(socket){
console.log('client connected to "secure" socket');
socket.on('disconnect', function(){
console.log('client disconnected from "secure" socket');
});
});
return http.createServer(app);
}
module.exports = Host;