如何使用 socket.io 和 laravel 发送用户特定数据?
How do I send user specific data with socket.io and laravel?
我不确定如何正确表达这个问题,但我开始了。我有 laravel、angular、节点 w/socket.io,我也在使用 JWT 进行身份验证。我的最终目标是能够向特定用户发送实时更新通知。对于我的生活,我似乎无法理解工作流程是怎样的。
我最初虽然是在握手中发送jwt然后在节点中使用然后做http请求来获取数据,然后return表示数据。换句话说,当触发特定事件时,节点将已经拥有令牌,将请求发送到 laravel 以获取特定信息。
有人可以向我解释如何在此架构中通过 socket.io 发送用户特定数据吗?
这让我走上了正确的轨道。
首先我需要将我的 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'));
});
此代码块中的请求returns 基于经过身份验证的令牌的用户对象。参考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);
});
我不确定如何正确表达这个问题,但我开始了。我有 laravel、angular、节点 w/socket.io,我也在使用 JWT 进行身份验证。我的最终目标是能够向特定用户发送实时更新通知。对于我的生活,我似乎无法理解工作流程是怎样的。
我最初虽然是在握手中发送jwt然后在节点中使用然后做http请求来获取数据,然后return表示数据。换句话说,当触发特定事件时,节点将已经拥有令牌,将请求发送到 laravel 以获取特定信息。
有人可以向我解释如何在此架构中通过 socket.io 发送用户特定数据吗?
这让我走上了正确的轨道。
首先我需要将我的 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'));
});
此代码块中的请求returns 基于经过身份验证的令牌的用户对象。参考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);
});