Laravel 6.x 公共廣播訊息筆記

小李世界發表於2019-10-28

環境

  • 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 協議》,轉載必須註明作者和本文連結
無論在現實或是網路中,我都是孤獨的。

相關文章