0

我已经按照这个聊天教程http://cestfait.ch/content/chat-webapp-nodejs创建了一个简单的聊天应用程序,我一直试图将其限制为只有 2 个用户,我想创建 2 个名为 user1id 的变量,和user2id,我希望它们成为客户端的socket.id,比如

// you set this value when the user1 connects
var user1id;

// you set this value when the user2 connects
var user2id;

// just for visualization, this is one of the questions I have on how to do this.
user1id = socket.id; user2id = socket.id;

我只想要 2 个用户并将他们作为 user1 和 user2 的原因是我可以比较他们的消息,所以我需要一组 user1 和用户 2 的消息,例如

user1arr = []; user2arr = [];

然后只需比较 user1 的“currentWord”变量,看看它是否与 user2msgs[] 中的任何内容匹配。user1 的例子如下:

function receivedWord(userid, currentWord) {

// this means current player is 1
if( userid == user1id ) {

    // adds the word received to user 1 word array
    user1arr.push(currentWord);

    // compares received word with each word in user 2 array
    $.each(user2arr, function(u2word) {
        if(u2word == currentWord) {
            wordsMatch();
        }
    }
}

我的代码基本上是我在本文开头给出的聊天应用程序的代码。

谢谢。

4

1 回答 1

1

您将遇到的问题是,每次用户重新加载页面时,来自 socketIO 的 socketID 都会改变。您需要做的是将诸如 sessionID 之类的东西附加到用户,这样您就知道即使他重新连接,他也是同一个用户。您将需要查看像expressJS甚至connect这样的 webframe,它们是 nodeJS 的高度灵活的中间件。我已经用 express 完成了这样的事情,所以让我用一些代码让你开始吧

//directories
var application_root = __dirname;

//general require
var express = require('express'),
        connect = require('connect'),
        http = require('http'),
        fs = require('fs');

//create express app
var app = express();

//create sessionStore
var sessionStore = new connect.session.MemoryStore();

//setup sessionKey
var secretKey = 'superdupersecret';

//configure express
app.configure(function() {

        //use body parser
        app.use(express.bodyParser());

        //override methods
        app.use(express.methodOverride());

        //cookies and sessions
        // BE AWARE: this lines have to be written before the router!
        app.use(express.cookieParser(secretKey));
        app.use(express.session({
                store: sessionStore,
                secret: secretKey,
                key: 'express.sid'
        }));

        //router
        app.use(app.router);

        //use static page in public folder
        app.use(express.static(path.join(application_root, 'public')));
});


//create the http server link to the new data http object of express 3
server = http.createServer(app);

//make server listen to 8080 and localhost requests
server.listen(8080, 'localhost', function() {
        console.log('Express Server running and listening');
});

//bind socket.io to express server by listening to the http server object
var io = require('socket.io').listen(server);

//set the authorization through cookies 
io.set('authorization', function(data, accept) {

        //check if header data is given from the user
        if (!data.headers.cookie) {

                //return false if no cookie was given
                return accept('Session cookie required!', false);
        }

        //parse cookie into object using the connect method
        //NOTE: this line is a hack, this is due to the fact
        //that the connect.utils.parseCookie has been removed
        //from the current connect module and moved to an own
        //instance called 'cookie'.
        data.cookie = connect.utils.parseSignedCookies(require('cookie').parse(decodeURIComponent(data.headers.cookie)), secretKey);

        //save session id based on exress.sid
        data.sessionID = data.cookie['express.sid'];

        //get associated session for this id
        sessionStore.get(data.sessionID, function(err, session) {
                if (err) {
                        //there was an error
                        return accept('Error in session store.', false)
                } else if (!session) {
                        //session has not been found
                        return accept('Session not found', false);
                }

                //successfully got the session, authed with known session
                data.session = session;

                //return the accepted connection
                return accept(null, true);
        });

});

//connection handler for new io socket connections
io.sockets.on('connection', function(socket) {

        //parse handshake from socket to io
        var hs = socket.handshake;

        //show session information
        console.log('New socket connection with sessionID ' + hs.sessionID + ' connected');

});

只需通读代码和注释即可了解它们在做什么。基本上你正在做的是创建一个快速服务器,让 socketIO 监听它,创建一个 sessionStore 以使其全局可用,用一个 secretKey 锁定它并将其设置为 socketIO 的授权方法。然后套接字所做的是与用户握手,然后将其链接到快速会话。这意味着 express sessionID 在整个会话期间保持不变,而 socketIO ids 一直在切换。

于 2012-11-25T10:42:58.410 回答