【发布时间】:2025-11-29 17:15:01
【问题描述】:
我正在尝试使用 Laravel 作为后端 API 客户端和 SPA 作为前端创建一个实时通知系统,我使用 React 作为前端,但对于下面的示例,我将使用一个简单的 Vue.Js和刀片,我创建了一个工作示例。
所以,总而言之,我有一个触发事件的路由,如下例所示:
Route::get('fire', function () {
// this fires the event
$user = App\Models\User::find(1);
event(new App\Events\CampaignUploadedWithSuccess($user, 'testing a notification'));
return "event fired";
});
它触发的事件如下所示
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class CampaignUploadedWithSuccess implements ShouldBroadcast
{
protected $user;
public $notification;
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @param $user
* @param $notification
*/
public function __construct($user, $notification)
{
$this->user = $user;
$this->notification = $notification;
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return ['notifications-channel.' . $this->user->id];
}
}
所以我正在一个名为notification-channel.{userId}的频道上广播
然后我有一个使用节点运行的 socket.js 文件。
看起来像这样
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('notifications-channel.1', function(err, count) {
});
redis.on('message', function(channel, message) {
console.log('Notification Recieved: ' + message);
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});
http.listen(3000, function(){
console.log('Listening on Port 3000');
});
使用node socket.js 运行服务器并触发事件执行我想要的如下操作:
快乐的日子!我正在向一个频道广播..
但是,我现在有一个名为 test.blade 的刀片文件,它将引入 Vue 和 Socket.io
看起来像这样
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
</head>
<body>
<h1>Notifications</h1>
<ul>
<li v-repeat="notification: notifications">@{{ notifications }}</li>
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.16/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js"></script>
<script>
var socket = io('http://localhost:3000');
new Vue({
el: 'body',
data: {
notifications: []
},
ready: function() {
socket.on('notifications-channel.1', function(data) {
alert(data.notification);
});
}
});
</script>
</body>
</html>
这里的目标是在 notification-channel.1 有数据广播到它时发出消息警报。然而这不起作用。
所以我的问题是,如何使用 socket.io、Laravel 和 Redis 向频道广播并使用该频道的广播。
我对私人频道以及如何只为一个用户创建频道也有些摸不着头脑。文档很好,但它没有提供如何实现这一点的真实示例以及如何让多个平台使用通知。
【问题讨论】:
标签: laravel sockets websocket socket.io laravel-5.4