如何使用laravel-echo-server在laravel广播中通过私有通道接收套接字

时间:2019-02-22 10:04:58

标签: php laravel vue.js socket.io

我使用带有redis / laravel-echo-server的Laravel 5.7进行广播。 前端是vuejs 目前,在公共频道的广播也在运作。 但在专用通道上不起作用,无法在前端接收套接字

以下是我的代码库。

此代码部分是用于验证的路由代码

Broadcast::channel('notification-{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

这是活动的一部分

class NotificationEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public $user;
    public function __construct(User $user)
    {
        //
        $this->user = $user;

    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('notification-' . $this->user->id);
    }

    public function broadcastWith()
    {
        return ['data' => 'this is message'];
    }

}

这是前端代码

//bootstrap.js
 window.Echo = new Echo({
    broadcaster: "socket.io",
    host: window.location.hostname + ":6001"
 });

//接收Vue文件

export default {
  mounted() {
    Echo.private("notification-" + window.Laravel.user).listen(
      "NotificationEvent",
      e => {
        console.log("there");
      }
    );
  }
};

joining to private channel is okay 但我无法从laravel事件收到任何消息

Route::get('test-broadcast', function () {
    $user = \App\User::findOrFail(1);
    broadcast(new NotificationEvent($user));
});

[2019-02-22 10:46:28] local.INFO: Broadcasting [App\Events\PrivateNotificationProcedure] on channels [private-notification-procedure-1] with payload:
{
    "socket": null
}  

我不确定是什么问题。

谢谢很多

1 个答案:

答案 0 :(得分:0)

运行命令php artisan config:clear 对我有用