2

在这里,我使用 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);
                });
            });
        });

});
4

1 回答 1

4

您尚未为您的socket.io. 默认情况下,与您的每个连接socket.io都是一个新连接,尽管它具有相同的 cookie(您的 cookie 中的 session_id )。有一个特殊的选项可以socket.io通过身份验证功能传递每个请求,例如:

var sAuthorization = function(req, cb) {
    if ( req.headers.cookie ) { 
        cb(null, true); return; // We have cookie
    } else {
        cb(null, false); return; // We don't have cookie drop the connection
    };

var socket = require('socket.io').listen(app, { authorization: sAuthorization });
    

你应该做的事情使它工作(我不会把它写成代码,因为需要做很多修改):

  1. 在 express中的初始连接中实现给用户一个名称http(每个用户都应该为他们的唯一会话指定一个用户名);
  2. 实现可以通过 express 和 socket.io 访问的 sessionStore(有关如何操作的一些想法,请参阅此要点nowjs(它使用但它是您必须查看的 sessionStore 代码)。实际上,如果您将 sessionStore 放在某个数据库中会更好,而不是在您的 MemoryStore 中。
  3. 使您的socket.io授权子到达此 sessionStore 并获取用户名,然后像往常一样将其作为此套接字的参数:socket.set('name', ....

差不多就是这样。这并不像听起来那么难,但这是正确的做法。

进一步阅读:

  1. https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO
  2. https://github.com/LearnBoost/socket.io/wiki/Authorizing

更新 :

看看这个答案,这对你 Securing Socket.io会很有帮助

更新二:

我在这里用该代码创建了一个 Gist 文件https://gist.github.com/1b17fd2a7b324cb3411a

var express = require('express'),
    app = express(),
    http = require('http'),
    server = http.createServer(app),
    users = 0,
    MemoryStore = express.session.MemoryStore,
    sessionStore = new MemoryStore(),
    parseCookie = require('cookie').parse,
    utils = require('connect').utils,
    io = require('socket.io').listen(server);

app.use( express.bodyParser() );
app.use( express.cookieParser('secret') );
app.use( express.session({secret: 'secret', store:sessionStore}) );

app.get('/', function(req, res) {
    var user = req.session.username ? req.session.username : null;
    if ( !user ) {
        user = 'user_' + users++;
        req.session.username = user;
        req.session.save();
    }
    res.send('<!doctype html> \
        <html> \
        <head><meta charset="utf-8"></head> \
        <body> \
            <center>Welcome ' + user + '</center> \
            <script src="/socket.io/socket.io.js"></script> \
            <script> \
                var socket = io.connect(); \
                socket.emit("message", "Howdy"); \
            </script> \
        </body> \
        </html>');
});

io.configure(function () {
    io.set('authorization', function (request, callback) {
        var cookie = parseCookie(request.headers.cookie);
        if( !cookie && !cookie['connect.sid'] ) {
            return callback(null, false);
        } else {
            sessionStore.get(utils.parseSignedCookie(cookie['connect.sid'], 'secret'), function (err, session) {
                if ( err ) {
                    callback(err.message, false);
                } else {
                    if ( session && session.username ) {
                        request.user = session.username;
                        callback(null, true);
                    } else {
                        callback(null, false);
                    }
                }
            });
        }
    });
});

io.sockets.on('connection', function (socket) {
    socket.on('message', function(msg) {
        console.log(msg + 'from '+ socket.handshake.user);
    });
});

server.listen(8000);
于 2013-01-31T12:46:55.237 回答