21. Laravel 模型关联:更多使用方法 – 1

Laravel 广播 – 公有广播

配套视频地址:https://www.bilibili.com/video/av78577184

配置

配置驱动 "pusher", "redis", "log", "null"          // .env
npm install --save socket.io-client |  echo 'websocket 客户端'
npm install --save laravel-echo     |  echo 'websocket 客户端封装'
npm install -g laravel-echo-server  |  echo 'websocket 服务端'
npm install                         |  echo '安装所有其他依赖'
npm run watch                        |  echo '监控文件变化编译前端资源'
laravel-echo-server init             |  echo '初始化 websocket 服务端'
laravel-echo-server start            |  echo '启动 websocket 服务端'

初始化 websocket 客户端

// bootstrap.js  最下
import Echo from "laravel-echo"

window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});

事件

<?php

namespace App\Events;

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 Free implements ShouldBroadcast           // 1. 事件是要广播出去的
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $msg;

    public function __construct($msg)           // 2. 广播出去的内容
    {
        $this->msg = $msg;
    }

    public function broadcastOn()               // 3. 对哪些频道进行广播
    {
        return [new Channel('countryside'), new Channel('a')];
    }
}

设置客户端监听广播

// bootstrap.js 最下 查看config/database.php redis前缀
window.Echo.channel('laravel_database_countryside')
    .listen('Free', (e) => {
        console.log(e);
    });

触发事件,广播开始

Route::get('/event', function () {
    event(new \App\Events\Free('免缴农业税啦'));
});

app.js 引用

// welcome.blade.php
<div id="app"></div>
<script src="js/app.js"></script>

posted on 2023-02-28 13:37  何苦->  阅读(28)  评论(0编辑  收藏  举报

导航