我使用 Redis 和 Socket.io 来设置实时更新,但 Laravel Echo 没有捕获事件。
如果我使用 io() 的实例,它就可以正常工作。这是我在我的 vue 应用程序中监听事件的代码:
不会捕捉事件
window.Echo.channel('users')
.listen('UserCreated', event => {
console.log(event);
this.all_users.push(event.user);
this.filter_data();
});
会捕捉事件
window.socket = io(window.location.origin+':3000');
window.socket.on('users:App\\Events\\UserCreated', function(data){
console.log(data);
console.log('from socket');
this.all_users.push(data.user);
this.filter_data();
}.bind(this));
我的节点 js 代码来推送事件。
var server = require('http').Server();
var io = require('socket.io')(server);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('users', function(error, count){
console.log(error);
console.log(count);
});
redis.on('message', function(channel, message){
console.log(channel);
message = JSON.parse(message);
console.log(message);
const emmitChannel = `${channel}:${message.event}`;
console.log(emmitChannel);
io.emit(emmitChannel, message.data);
});
server.listen(3000);
我的 Laravel 事件广播
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
//Models
use App\User;
class UserCreated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(User $user)
{
$this->user = $user;
$this->dontBroadcastToCurrentUser();
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return ['users'];
}
}
我尝试更改事件传递给 Laravel Echo 的方式,因为默认情况下它会接收它们,users:App\Events\UserCreated
但我没有运气。