0

我正在尝试使用sailsjs 创建一个实时应用程序。我在 youtube 上看到了教程,在该网站上搜索了简单的解决方案。在 github 上搜索了简单的示例运行示例。我发现一些工作,但旧版本。无论我学到什么,发现我都试图在我的应用程序中实现。

那就是 sessionController.js

var bcrypt = require('bcrypt');
module.exports = {
 'login':function  (req, res) {
    if (req.isSocket) {
        return res.json({status: 403, redirectTo: "/sess/new"});
    } else {
         res.view('sess/new');
    }
 },
 'create': function  (req,res, next) {
    if (!req.param('email') || !req.param('password')) {
        var usernamePasswordRequiredError = [{name : 'usernamePasswordRequired',         message:'You must enter both username and password'}]
        req.session.flash ={
            err: usernamePasswordRequiredError
        }
        res.redirect('/session/login');
        return;
    }
    User.findOneByEmail(req.param('email'), function  (err, user) {
        if (err) return next(err);
        if (!user) {
            var noAccountError = [{name:'noAccount', message:'The email address '+req.param('email')+' not found'}];
            req.session.flash = {
                err:noAccountError
            }
            res.redirect('/session/login');
            return;
        };
        bcrypt.compare(req.param('password'), user.password, function  (err, valid) {
            if (err) return next(err);
            if (!valid) {
                var usernamePasswordMismatchError = [{name:'usernamePasswordMismatch', message:'Invalid username and password combination'}]
                req.session.flash = {
                    err: usernamePasswordMismatchError
                }
                res.redirect('/session/login');
                return;
            };
            req.session.authenticated = true;
            req.session.User = user;
            user.online = true;

            user.save(function  (err,user) {
                if (err) return next(err);
                // Inform other sockets (e.g. connected sockets that are subscribed) that this user is now logged in
                console.log('loged in publishUpdate');
                User.publishUpdate(user.id, {
                    loggedIn: true,
                    id: user.id,
                    name: user.fillname,
                    action: ' has logged in.'
                });


                if (req.session.User.admin) {
                    res.redirect('/user');
                    return;
                };
            });

            res.redirect('/user/');

        });
    });

},
'logout':function  (req, res, next) {

    User.findOne(req.session.User.id, function foundUser (err, user) {
        var userId = req.session.User.id;
        User.update(userId,{
            online:false
        }, function  (err) {
            if (err) return next(err);

            // Inform other sockets (e.g. connected sockets that are subscribed) that the session for this user has ended.
                User.publishUpdate(userId, {
                    loggedIn: false,
                    id: userId,
                    name: user.fullname,
                    action: ' has logged out.'
                });

            req.session.destroy();
            return res.redirect('/session/login');
        });
    });

  }
 };

那就是 userController.js

 module.exports = {

'signup':function (req, res) {

    if (req.isSocket) {
        return res.json({status: 403, redirectTo: "/user/signup"});
    } else {

        res.view();
    }
},

'create': function (req, res, next) {
    console.log("got sothing "+req.param('fullname'));
    //"req: "+req.param('fullname')
    var params = {
        'fullname' : req.param('fullname'),
        'username' : req.param('username'),
        'email' : req.param('email'),
        'password' : req.param('password')
    };

    User.create( params,function userCreated(err, user) {
        if (err) {
            req.session.flash = {
                err:err
            }
            return res.redirect('/user/signup');
        }

        req.session.authenticated = true;
        req.session.User = user;

        user.online = true;
        user.save(function  (err, user) {
            if (err) return next(err);

            User.publishCreate(user);
            res.redirect('/user/show/'+user.id);
        });


    });
 },

 'update': function (req, res, next) {


    var id = req.param('id');

    var params = {
        'fullname' : req.param('fullname'),
        'username' : req.param('username'),
        'email' : req.param('email')
    };

    User.update(req.param('id'), req.params.all(), function userUpdated(err, user) {
        if(err){
            return res.redirect('/user/edit/'+id);
        } //return// next(err);
        User.publishUpdate(user);
        res.redirect('/user/show/'+id);
    });
},

'show':function (req, res, next) {
  var id = req.param('id');

    User.findOne(req.param("id"), function foundUser (err, user) {
        if(err) return next(err);
        if(!user) return next();

        User.publishUpdate(user);

        res.view({
            user:user
        });
    });
},

'index':function (req, res, next) {

    User.find(function foundUsers (err, users) {
        if(err) return next(err);

        if (req.isSocket) {
            return res.json({status: 403, redirectTo: "/user"});
        } else {

            res.view({
                users:users
            });
        }

    });
},
'edit':function (req, res, next) {

 console.log("got sothing "+req.param('id'));
 var id = req.param('id');

    User.findOne(req.param("id"), function foundUser (err, user) {
        if(err) return next(err);
        if(!user) return next('User does\'t exist.');
        res.view({
            user:user
        });
    });
},
destroy :function (req, res, next) {
    User.findOne(req.param('id'), function foundUser (err, user) {
        if (err) return next(err);
        if (!user) return next('User does\'t exist.');
        User.destroy(req.param('id'), function userDestroyed (err) {
            if (err) return next(err);

            //publish
            User.publishUpdate(user.id, {
                name: user.fullname,
                action: ' has been destroyed.'
            });

            // Let other sockets know that the user instance was destroyed.
            User.publishDestroy(user.id);

        });
        res.redirect('/user');
    });
},
'subscribe':function  (req, res) {
    User.find(function foundUsers (err, users) {

    User.subscribe(req.socket, users);
    res.send(200);
});
}

 };

那就是 app.js 来接收数据

io.socket.on('connect', function messageReceived() {
  console.log(this.socket.sessionid);

   this.socket.on('message', function (tmessage) {

    console.log(tmessage);
    this.socket.get('/user/subscribe');

  });

});

问题很简单,当用户注册或注销或用户执行任何操作时,我都没有得到响应。我认为我正确地发布了操作,但不知道接收。如果有人能指出我正确的方向,那将非常有帮助。如果需要,我可以分享更多信息。
我将在github上分享这个。所以这将对其他人有充分的帮助。
谢谢。

4

2 回答 2

3

您是否阅读过资源丰富的 pub-sub的官方文档?它声明的第一件事是你应该监听以模型命名的事件——所以如果你想听到你的模型发生的事情User,你需要做:

io.socket.on('user', ...)

不是

io.socket.on('message', ...)

其次,正如 Jason 上面提到的,您需要将您的套接字订阅到您想要接收通知的实例。您可以使用自定义subscribe操作来做到这一点,但如果您打开了 REST 蓝图(默认设置),那么该操作并不是必需的;只是在做

io.socket.get('/user', function(data){} )

将请求套接字订阅所有返回的User实例。有关更多信息,请参阅blueprint .find()的文档。这个调用不需要出现在io.socket.on调用之前,但它不能出现在处理程序中,因为它永远不会被调用。因此,您可以将客户端代码重写为:

io.socket.on('connect', function socketConnected() {
  console.log(this.socket.sessionid);

   // Respond to user events.  You can always safely use the 
   // global `io.socket` to bind event handlers
   io.socket.on('user', function (tmessage) {

    console.log(tmessage);

   });

   // Get the users and just spit them out to the console.  This will also
   // subscribe the socket to any events involving the returned users, which 
   // will then be handled by the `io.socket.on` code above.
   io.socket.get('/user', console.log.bind(console));


});

有关工作中各种套接字方法的良好演示,请参阅SailsChat示例应用程序。

于 2014-09-07T19:38:46.507 回答
0

您的app.js代码似乎暗示您subscribe在收到来自套接字的消息时触发了该操作。

...
this.socket.on('message', function (tmessage) {
    console.log(tmessage);
    this.socket.get('/user/subscribe');
});
...

这可能是它失败的原因,因为套接字尚未与集合关联,因此它不会收到任何消息。尝试将套接字订阅调用移到消息处理程序之外。

...
this.socket.get('/user/subscribe');
this.socket.on('message', function (tmessage) {
    console.log(tmessage);
});
...
于 2014-09-06T18:21:19.990 回答