【问题标题】:How do I send user specific data with socket.io and laravel?如何使用 socket.io 和 laravel 发送用户特定的数据?
【发布时间】:2016-05-22 08:04:33
【问题描述】:

我不知道如何正确地表达这个问题,但我开始了。我有 laravel、angular、node w/socket.io,我也使用 JWT 进行身份验证。我的最终目标是能够向特定用户发送实时更新通知。对于我的生活,我似乎无法理解工作流程会是怎样的。

我最初的想法是在握手中发送 jwt,然后在节点中使用 then 来执行 http 请求以获取数据,然后返回所述数据。换句话说,当特定事件被触发时,节点将已经拥有令牌,向 laravel 发送请求以获取特定信息。

有人可以向我解释一下如何在这个架构中通过 socket.io 发送用户特定的数据吗?

【问题讨论】:

    标签: angularjs node.js laravel socket.io jwt


    【解决方案1】:

    我发现了这篇很棒的文章:https://www.ukietech.com/blog/programming/step-by-step-instruction-of-setting-up-real-time-secure-broadcasting-with-laravel-5-1-socket-io-and-redis/

    这让我走上了正轨。

    首先我需要将我的 JWT 传递到套接字中:

    var socket = io('http://192.168.10.10:3000', {query: "Authorization="+$rootScope.$storage.satellizer_token});
    

    接下来,我实际上再次验证了令牌。我知道这可能有点矫枉过正,但我​​想知道撞到插座的东西是合法的。

    io.use(function(socket, next){
    if (socket.handshake.query.Authorization) {
    
        var config = {
            url:'http://192.168.10.10/api/auth',
            headers:{
                Authorization:'Bearer '+socket.handshake.query.Authorization
            }
        };
    
        request.get(config,function(error,response,body){
    
            socket.userId = JSON.parse(body).id;
            next();
        });
    
    }
    // call next() with an Error if you need to reject the connection.
    next(new Error('Authentication error'));
    

    });

    此代码块中的请求根据经过身份验证的令牌返回一个用户对象。更多信息请参考JWTAuth

    然后在连接时,我会将用户分配到一个唯一的频道。

     io.on('connection',function(socket){
       socket.join('userNotifications.'+socket.userId);
        console.log('user joined room: userNotifications.'+socket.userId);
    });
    

    然后广播事件:

        notifications.on('pmessage', function(subscribed, channel, message) {
        var m = JSON.parse(message);
        io.emit(channel+":"+m.event, message);
    });
    

    回到客户端,我监听频道。 var user 是用户 ID。

    socket.on('userNotifications.'+ user+':App\\Events\\notifications', function(message){
                            console.log(message);
                        });
    

    【讨论】:

      猜你喜欢
      • 2021-10-28
      • 2019-02-05
      • 2014-08-14
      • 1970-01-01
      • 2012-07-08
      • 2011-06-06
      • 2020-02-26
      • 2017-06-26
      • 1970-01-01
      相关资源
      最近更新 更多