如何在Laravel中通过Socket.io获取Notifications事件的$message动态数据
实现Laravel事件数据推送至Socket.io前端
现有代码概述
你已完成Socket.io服务端搭建、前端Socket连接、Laravel Notifications 事件定义,现在需要将事件中的$message动态数据推送到前端Socket客户端。
实现步骤
1. 在Laravel中安装Socket.io客户端
在Laravel项目根目录执行命令安装依赖:
npm install socket.io-client
2. 创建事件监听器
生成监听Notifications事件的监听器:
php artisan make:listener SendNotificationToSocket
打开生成的app/Listeners/SendNotificationToSocket.php,替换代码如下:
<?php namespace App\Listeners; use App\Events\Notifications; use SocketIO\Client; class SendNotificationToSocket { public function handle(Notifications $event) { // 连接到Socket.io服务端 $client = new Client('http://localhost:3000'); // 将事件中的消息发送到Socket服务端 $client->emit('laravelNotification', [ 'message' => $event->message ]); $client->disconnect(); } }
3. 注册事件与监听器
打开app/Providers/EventServiceProvider.php,在$listen数组中添加关联:
protected $listen = [ Notifications::class => [ SendNotificationToSocket::class, ], ];
4. 修改Socket.io服务端代码
更新server.js,添加接收Laravel事件并广播给前端的逻辑:
const server = require("http").createServer(); const io = require("socket.io")(server, { cors: { origin: "*", methods: ["GET", "POST"], }, }); const port = 3000; server.listen(port, () => { console.log(`Socket.io server listening on port ${port}`); }); io.on("connection", (socket) => { console.log("New client connected"); // 接收Laravel传来的通知数据 socket.on('laravelNotification', (data) => { // 广播给所有已连接的前端客户端 io.emit('notificationData', { message: data.message }); }); socket.on("disconnect", () => { console.log("Client disconnected"); }); });
5. 更新前端Blade脚本
修改前端脚本,移除主动测试消息的逻辑,专注接收服务端广播:
<script> const socket = io('http://localhost:3000'); socket.on('connect', () => { console.log('Connected to Socket.io server'); }); // 接收服务端广播的通知数据 socket.on('notificationData', (data) => { console.log('Received notification data:', data.message); // 此处可添加通知渲染到页面的逻辑 }); socket.on('disconnect', () => { console.log('Disconnected from Socket.io server'); }); $(document).ready(function() { $('#license_held_image_input').change(function(e) { var reader = new FileReader(); reader.onload = function(event) { $('#preview_image').attr('src', event.target.result); } reader.readAsDataURL(e.target.files[0]); }); }); </script>
6. 触发事件测试
在Laravel的控制器、命令行或其他逻辑中触发Notifications事件:
event(new \App\Events\Notifications('这是一条来自Laravel的动态通知!'));
此时前端控制台会打印出接收到的通知消息。
内容的提问来源于stack exchange,提问作者Ashish kumar
相关产品推荐
相关产品推荐

