Browse Source

ws测试7

master
wanghongjun 6 days ago
parent
commit
ff56b9a572
  1. 32
      app/Events/SendAnnouncement.php
  2. 5
      routes/admin/api.php

32
app/Events/SendAnnouncement.php

@ -2,7 +2,6 @@
namespace App\Events;
use Carbon\Carbon;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
@ -13,36 +12,27 @@ class SendAnnouncement implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public string $message;
public string $broadcastTime;
public $message;
/**
* Create a new event instance.
*/
public function __construct(string $message) {
public function __construct($message)
{
$this->message = $message;
$this->broadcastTime = Carbon::now()->toDateTimeString();
}
/**
* Get the channels the event should broadcast on.
*
* @return array<int, Channel>
*/
public function broadcastOn(): array {
// 定义事件要广播到的公共频道
public function broadcastOn(): array
{
return [
new Channel('channel-pub'),
new Channel('test-channel'), // 公共频道
];
}
/**
* @return array
*/
public function broadcastWith(): array {
// 可选:自定义广播数据
public function broadcastWith(): array
{
return [
'name' => 'MyTestEvent',
'message' => $this->message,
'broadcastTime' => $this->broadcastTime
'time' => now()->toDateTimeString(),
];
}
}

5
routes/admin/api.php

@ -51,11 +51,6 @@ Route::group(['prefix' => 'admin'], function () {
Route::post('/login', [AuthController::class, 'login']);
// get测试区
Route::get('/test_broadcast', function () {
\App\Events\SendAnnouncement::dispatch("Hello, this is a real-time message!");
return 'Event broadcasted!';
});
// 需要认证的接口
Route::middleware(['admin.auth'])->group(function () {

Loading…
Cancel
Save