在这里,我使用 get of socket-io 并且在每次重新加载页面时它都会给我新的值(理想情况下它应该来自会话并且应该相同)。你能指出原因吗?
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var _ = require('lodash');
var q = require('q');
server.listen(3000);
var userCounter = 0;
app.use(express.cookieParser());
app.use(express.cookieSession({secret: 'secret', key: 'express.sid', cookie:{ path: '/', httpOnly: true, maxAge: (1000*3600*24)} }));
app.use(express.static('public'))
.use(function (req, res) {
res.end('File not available\n');
});
function getUserName(socket) {
var deferred = q.defer();
socket.get('userName', function (err, Name) {
if (err || !Name) { // PROBLEM: It always goes in to this IF
var userName = "Userno: " + (userCounter + 1);
userCounter++;
socket.set('userName', userName, function () {
deferred.resolve(userName);
});
} else {
deferred.resolve(Name);
}
});
return deferred.promise;
}
io.sockets.on('connection', function (socket) {
getUserName(socket).
then(function (userName) {
socket.emit("welcome", userName);
_(io.sockets.sockets).forEach(function (eSocket) {
if (socket !== eSocket)
eSocket.emit("userAdded", userName);
});
socket.on('disconnect', function () {
socket.get('userName', function (err, userName) {
io.sockets.emit('userRem', userName);
});
});
});
});