私有频道发送消息给用户失败
我现在想要通过私有频道发送一个消息给用户,通过我自己服务器上 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 上的

请问我应该如何修复这个错误呢?谢谢各位
关于 LearnKu
pusher包安装了吗?
看一下 ws 的 messages 是否有返回 401 或者 403 之类的错误码
谢谢 @L学习不停 和 @Linxb 的解答~
最后我解决了,是因为我是在异步队列里面进行的广播事件的触发,所以应该继承的是 ShouldBroadcostNow 接口,而不是默认的 ShouldBroadcost 接口 (广播队列)