1

我用nodejs. 我express 3用作框架和socket.io客户端服务器通信。目前我正在尝试创建一个注册表单。它工作得很好,但我不确定如何正确使用socket.ioexpress一起使用。

我检查电子邮件和密码是否有效,如果不是,我想向客户端推送一个 json 对象。

我使用这个应用程序路线:

app.post('/user', function (req, res) {
    var user = new User(req.body.user), 
        errors;

    function userSaveFailed() {
        res.render('index');
    }

    errors = user.validation(req.body.user.confirm);
    user.save(errors, function (err) {
        if (err) {
            // Here I would like to send the Object to the client.
            io.sockets.on('connection', function (socket) {
                socket.emit('registration', {
                    errors : errors
                });
            });
            return userSaveFailed();
        }
        res.render('user/new.jade');
    });
});

好吧,客户端得到了 json 对象,但是如果另一个客户端连接到'/'他也得到了对象。我想我用socket.io错了。.emit()在应用程序路由中使用 a 的常用方法是什么?socket.io是否有必要express为此测试使用全局授权?

4

1 回答 1

1

one way to do that (if you really want to use socket.io to reply to a post, which you probably shouldn't), is to use one room per user session.

so on the on("connection", ...) do something like so:

socket.join(room) where room is something unique to the session (like the session id for example).

then to send back to only one user:

socketio.of('/')['in'](room).emit(...);, room being that same unique id used above.

于 2013-01-28T23:14:47.923 回答