You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel本地环境WebSocket消息未接收问题排查

Laravel实时通知系统事件无法送达问题排查

我正在搭建一个实时通知系统,已成功建立WebSocket连接并订阅private-notifications频道,但触发事件后,接收页面的网络和控制台均无相关事件信息,事件无法送达。

相关配置与代码

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' => false,
                'host' => '127.0.0.1',
                'port' => 6001,
                'scheme' => 'http'
            ],
        ],
]

.env

BROADCAST_DRIVER=pusher
PUSHER_APP_ID=app-id
PUSHER_APP_KEY=app-key
PUSHER_APP_SECRET=app-secret
PUSHER_APP_CLUSTER=ap1

Events/CommentCreated.php

class CommentCreated implements ShouldBroadcast
{
        public function broadcastOn()
        {
            return new PrivateChannel('notifications');
        }
}

routes/channels.php

Broadcast::channel('notifications', function ($user) {
    return true;
});

resources/js/bootstrap.js

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'app-key',
    wsHost: window.location.hostname,
    wsPort: 6001,
    forceTLS: false,
    disableStats: true,
    cluster: 'ap1',
    authEndpoint: 'http://localhost/project/public/broadcasting/auth'
});

resources/js/app.js

require('./bootstrap');

window.Echo.private('notifications')
    .listen('CommentCreated', (e) => {
        console.log('test');
});

routes/web.php

Route::get('send', function(){
    event(new CommentCreated('test'));
});

Route::get('receive', function(){
    echo '<script src="' . asset('js/app.js') . '"></script>';
});

连接状态确认

访问http://localhost/project/public/receive时,网络标签显示已成功建立连接并订阅频道:

{"event":"pusher:connection_established","data":"{\"socket_id\":\"154066640.435471633\",\"activity_timeout\":30}"}

{"event":"pusher:subscribe","data":{"auth":"app-key","channel":"private-notifications"}}

{"event":"pusher_internal:subscription_succeeded","channel":"private-notifications"}

问题原因及解决方案

1. 队列配置未正确设置

Laravel事件广播默认依赖队列驱动,若未配置队列或队列未启动,事件会无法广播:

  • 临时测试:在.env中设置QUEUE_CONNECTION=sync,强制事件同步广播
  • 生产环境:配置队列驱动(如database)并启动队列监听:php artisan queue:work

2. 事件类未正确处理数据与广播名称

当前CommentCreated类未接收并存储传递的参数,且未明确广播别名,导致前端无法正确匹配:
修改事件类:

class CommentCreated implements ShouldBroadcast
{
    public $message;

    // 接收构造参数并存储
    public function __construct($message)
    {
        $this->message = $message;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('notifications');
    }

    // 定义广播别名,方便前端监听
    public function broadcastAs()
    {
        return 'CommentCreated';
    }
}

3. 前端监听事件名称不匹配

若后端事件使用了命名空间,前端需要通过别名或完整命名空间监听,修改app.js:

window.Echo.private('notifications')
    // 使用点号开头匹配别名,避免命名空间冲突
    .listen('.CommentCreated', (e) => {
        console.log('收到通知:', e.message);
});

4. Laravel WebSocket服务未启动

配置中指向本地6001端口,需确保laravel-websockets服务已运行:

  • 启动服务:php artisan websockets:serve
  • 检查端口6001是否被占用,确保服务正常监听

5. 前端JS资源未重新编译

若使用Laravel Mix管理前端资源,需重新编译确保代码生效:

  • 运行npm run dev或npm run watch编译JS文件

内容的提问来源于stack exchange,提问作者user25934652

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 16:03:24