服务端代码,有一个问题
handshakeData.username = username;
这个好像不起作用
var connectedUsers = [];
io.set('authorization', function (handshakeData, callback) {
var signedCookies = require('express/node_modules/cookie').parse(handshakeData.headers.cookie);
handshakeData.cookies = require('express/node_modules/connect/lib/utils').parseSignedCookies(signedCookies, settings.cookie_secret);
sessionStore.get(handshakeData.cookies['connect.sid'], function(err, session) {
if (err) {
callback(err, false);
return;
}
var username = session.user && session.user.name;
handshakeData.username = username; //这个好像不起作用
console.log('authorization', username);
console.dir(connectedUsers);
if (connectedUsers.indexOf(username) !== -1) {
//重复登录
console.log('重复登录');
callback('重复登录', false);
} else {
connectedUsers.push(username);
callback(null, true);
}
});
//callback(null, false);
});
io.of('/client').on('connection', function (socket) {
socket.emit('agents', agents);
socket.emit('rate', rate);
//socket.handshake.username
console.log('client connect:', socket.client.request.username);
//client下线
socket.on('disconnect', function() {
console.log('disconnect', socket.client.request.username);//socket.handshake.username);
connectedUsers.splice(connectedUsers.indexOf(socket.client.request.username), 1);
});
});
客户端代码
var client = io.connect('/client');
// 下面代码参考官方文档,但没有收到连接失败端消息,请大家指正
client.on('connect_failed', function (reason) {
console.log('unable to connect to namespace', reason);
});