Laravel通过Broadcasting系统结合laravel-websockets实现WebSocket,先配置广播驱动并安装laravel-websockets包,创建实现ShouldBroadcast的事件,设置私有频道授权逻辑,前端使用Laravel Echo连接WebSocket服务器并监听事件,后端通过触发事件实现实时通信。

Laravel 的 WebSocket 功能通过 Broadcasting(广播)系统实现,结合 Laravel Echo 和第三方服务(如 Pusher、Redis、Soketi 或 laravel-websockets 扩展包),可以轻松实现实时通信。下面一步步说明如何在 Laravel 中实现 WebSocket 广播。
Laravel 自带广播系统,但默认是关闭的。你需要先启用并选择合适的广播驱动。
步骤:
BROADCAST_DRIVER=pusher如果你用的是本地开发且不想依赖外部服务,推荐使用 laravel/websockets 包,它兼容 Pusher 协议且可自托管。
这个包由 BeyondCode 开发,能让你无需 Pusher 就运行 WebSocket 服务器。
安装命令:
composer require beyondcode/laravel-websockets发布资源:
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider"执行后会生成配置文件和迁移。然后运行:
php artisan migrate启动 WebSocket 服务器:
php artisan websockets:serve默认监听 localhost:8080,你可以在浏览器访问 /laravel-websockets 查看仪表盘。
Laravel 使用事件来触发广播消息。创建一个可广播的事件:
php artisan make:event MessageSent编辑该事件类,实现 ShouldBroadcast 接口:
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct($message)
{
$this->message = $message;
}
public function broadcastOn()
{
return new PrivateChannel('chat.' . $this->message['user_id']);
}
public function broadcastAs()
{
return 'message.sent';
}
}
这里使用了私有频道,需要授权访问。你也可以用 PublicChannel 实现公开广播。
在 routes/channels.php 中定义频道授权逻辑:
Broadcast::channel('chat.{userId}', function ($user, $userId) {
return (int) $user->id === (int) $userId;
});
确保用户只能订阅属于自己的频道。
在前端引入 Laravel Echo 和 Socket.io 客户端。
安装依赖:
npm install --save laravel-echo pusher-js配置 Echo(通常在 resources/js/bootstrap.js):
import Echo from "laravel-echo";
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your-pusher-key',
wsHost: window.location.hostname,
wsPort: 8080,
wssPort: 8080,
forceTLS: false,
disableStats: true,
encrypted: true,
enabledTransports: ['ws', 'wss'],
});
注意:这里的 key 是你在 .env 中设置的 PUSHER_APP_KEY,即使使用 laravel-websockets 也需要配置。
在页面中监听广播事件:
window.Echo.private(`chat.${userId}`)
.listen('message.sent', (e) => {
console.log(e.message);
});
当后端触发 MessageSent 事件时,客户端就会收到实时消息。
在控制器或任务中分发事件即可发送广播:
event(new MessageSent([
'user_id' => $userId,
'content' => 'Hello World'
]));
只要事件实现了 ShouldBroadcast,Laravel 就会自动通过配置的驱动推送消息。
基本上就这些。整个流程就是:定义事件 → 配置广播驱动 → 前端连接并监听 → 后端触发事件。不复杂但容易忽略授权和端口配置。调试时记得开 websockets:serve 并检查浏览器控制台是否有连接成功。基本上就这些。
以上就是Laravel websocket怎么实现_Laravel Broadcasting广播系统教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号