私有频道发送消息给用户失败

我现在想要通过私有频道发送一个消息给用户,通过我自己服务器上 websockets

后端

routes/channel.php

use Illuminate\Support\Facades\Broadcast;
use App\Models\User;

Broadcast::channel('users.{id}', function (User $user, Int $id) {
    return (int) $user->id === (int) $id;
});

app/Events/NewPrivateMessage.php

...
class NewPrivateMessage implements ShouldBroadcast{

    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(Message $message){
        $this->message = $message;
    }

    public $message;

    public function broadcastOn(){
        return new PrivateChannel('users.'.$this->message->user_id);
    }

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

config/broadcasting.php

...
    'connections' => [
        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'encrypted' => true,
                'host' => '127.0.0.1',
                'port' => 6001,
                'scheme' => 'http'
            ],
        ],
        ...
    ],

前端

...
import Echo from 'laravel-echo';

window.SPY = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true,
    auth: {
        headers: {
            Authorization: `${store.state.auth.token.token_type} ${store.state.auth.token.access_token}`
        }
    }
});

window.SPY.private(`users.${store.state.auth.user.id}`)
    .listen('NewPrivateMessage', (e) => {
        console.log(e);
    });

我尝试在 tinker 中运行以下代码,但没有任何反应,没有 log 也没有 console.log()

broadcast(new \App\Events\NewPrivateMessage(\App\Models\Message::first()));

我确定已经移除了 config/app.php 中对 BroadcastServiceProvider 的注释,并且我连接私有频道时验证成功的

私有频道发送消息给用户失败

并且我是连接到 websocket 上的

私有频道发送消息给用户失败

请问我应该如何修复这个错误呢?谢谢各位

stackoverflow.com 上这个问题也是我提的

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 3

pusher包安装了吗?

3年前 评论
家猪配种专家 (楼主) 3年前

看一下 ws 的 messages 是否有返回 401 或者 403 之类的错误码

3年前 评论

谢谢 @L学习不停@Linxb 的解答~

最后我解决了,是因为我是在异步队列里面进行的广播事件的触发,所以应该继承的是 ShouldBroadcostNow 接口,而不是默认的 ShouldBroadcost 接口 (广播队列

class NewPrivateMessage implements ShouldBroadcastNow{...}
3年前 评论
L学习不停 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!