我发现了这篇很棒的文章: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);
});