Laravel 6.x 公共广播消息笔记

环境

  • Laravel 6.0.4 并部署好,包括 Redis 和 PhpRedis
  • macOS

后端

配置修改

启用 config/app.conf 中的广播服务提供者

App\Providers\BroadcastServiceProvider::class,

使用 Redis 驱动和队列同步模式

vim .env

BROADCAST_DRIVER=redis
QUEUE_CONNECTION=sync

Redis prefix 去掉

vim config/databases.php

'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'), 改为 'prefix' => '',,或注释。

WebSocket Server

安装

npm install -g laravel-echo-server

初始化,生成配置

laravel-echo-server init

根据提示,输入且回车。

? Do you want to run this server in development mode? (y/N) # Y,教程是在本地开发环境,
? Which port would you like to serve from? (6001) # 回车,WebSocket Server 服务端口
? Which database would you like to use to store presence channel members? (Use arrow keys) # redis
? Enter the host of your Laravel authentication server. (http://localhost) # http://127.0.0.1:8000 ,php artisan serve 的地址
? Will you be serving on http or https? (Use arrow keys) # 上面就是 http
? Do you want to generate a client ID/Key for HTTP API? (y/N) # y
? Do you want to setup cross domain access to the API? (y/N) # y
? What do you want this config to be saved as? (laravel-echo-server.json) # 回车

它会保存到 ./laravel-echo-server.json,你或许想打开看看(English 翻译 233)

事件

新建事件

php artisan make:event TestBroadcastingEvent

文件内容如下

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class TestBroadcastingEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $message;

    public function __construct($message)
    {
        $this->$message = $message;
    }

    public function broadcastOn()
    {
        return new Channel('push');
    }

    # 或者可以指定返回的格式和数据
    public function broadcastWith()
    {
        return [
            'data' => $this->message
        ];
    }
}

随便取了个频道名(公共频道),返回数据是 ['data' => 你的信息]

开启 WebSocket 服务

laravel-echo-server start

前端

安装

npm install --save laravel-echo
npm install --save socket.io-client

设置和接收

vim ./resources/js/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'
});

window.Echo.channel('push')
  .listen('TestBroadcastingEvent', (e) => {
    console.log(e);
  });

前端编译和 Web Server

npm run watch-poll
php artisan serve

验收

open http://127.0.0.1:8000

在路由或者 console.php 等等随便你喜欢的地方运行以下命令,以触发广播

broadcast(new App\Events\TestBroadcastingEvent('233'));

谷歌开发者工具 console 即可看到信息。

修改成支持 HTTPS

可以用 Beyond Compose 对比

{
        "authHost": "https://233.sx",
        "authEndpoint": "/broadcasting/auth",
        "clients": [
                {
                        "appId": "****************",
                        "key": "********************************"
                }
        ],
        "database": "redis",
        "databaseConfig": {
                "redis": {},
                "sqlite": {
                        "databasePath": "/database/laravel-echo-server.sqlite"
                }
        },
        "devMode": false,
        "host": null,
        "port": "6001",
        "protocol": "https",
        "socketio": {},
        "secureOptions": 67108864,
        "sslCertPath": "/root/.acme.sh/233.sx/fullchain.cer",
        "sslKeyPath": "/root/.acme.sh/233.sx/233.sx.key",
        "sslCertChainPath": "/root/.acme.sh/233.sx/ca.cer",
        "sslPassphrase": "/etc/nginx/dhparams.pem",
        "subscribers": {
                "http": true,
                "redis": true
        },
        "apiOriginAllow": {
                "allowCors": true,
                "allowOrigin": "https://233.sx",
                "allowMethods": "GET, POST",
                "allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
        }
}

其他

记得把 laravel-echo-server.json 写入 git 的 .gitignore 哦。

参见

按顺序,部分可能忘记列出了

本作品采用《CC 协议》,转载必须注明作者和本文链接
无论在现实或是网络中,我都是孤独的。
附言 1  ·  4年前

如果有遗漏、错误、建议,请告知,谢谢!

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 1

我重新设计了https://fnworks.com, 有时间可以看一下😄

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!