kanata-php/conveyor-laravel-broadcaster

该包最新版本(0.1.9)没有可用的许可证信息。

Conveyor Laravel Broadcaster

0.1.9 2024-05-10 02:57 UTC

This package is auto-updated.

Last update: 2024-09-10 12:49:12 UTC


README

这是Socket Conveyor的Laravel集成。它允许您将Conveyor WebSocket服务器作为Laravel的广播驱动程序使用。此包需要Jacked Server

此包是为那些想使用Conveyor作为广播驱动程序的用户提供的替代方案。为此,您需要安装Jacked Server或检查如何使用Conveyor运行您的WebSocket服务器。

安装

首先安装Jacked Server

步骤 1:通过composer安装包

composer require kanata-php/conveyor-laravel-broadcaster

步骤 2:发布配置

php artisan vendor:publish --provider="Kanata\LaravelBroadcaster\ConveyorServiceProvider"

步骤 3:将服务提供者添加到config/app.php文件中

<?php
return [
    // ...
    'providers' => [
        // ...
        Kanata\LaravelBroadcaster\ConveyorServiceProvider::class,
    ],
    // ...
];

步骤 4:如果在Laravel 11上,启用Laravel广播

php artisan install:broadcasting

步骤 5:将以下内容添加到您的config/broadcasting.php文件中

<?php

return [
    // ...
    'conveyor' => [
        'driver' => 'conveyor',
    ],
];

步骤 6:通过在routes/channels.php中添加以下内容来保护您的频道(特定于Laravel的详细内容)

use App\Models\User;
use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('actions-channel', function (User $user) {
    return true; // we are authorizing any user here - update according to your needs!
});

步骤 7:此包需要用户进行身份验证。要快速创建用户,您可以使用tinker

php artisan tinker

在tinker中,您可以创建一个用户

App\Models\User::factory()->create(['email' => 'user@jacked-server.com', 'password' => Hash::make('password')]);

步骤 8:在.env文件中指定WebSocket服务器的配置

重要:由于SQLite的锁定机制和此服务中的并发性,SQLite可能不会很好地工作。建议使用MySQL、Postgres或其他更健壮的数据库。

# ...
BROADCAST_CONNECTION=conveyor
# ...
# MySQL of Postgres are better alternatives that SQLite
CONVEYOR_DATABASE=pgsql
JACKED_SERVER_WEBSOCKET_ENABLED=true
# ...

此时,您可以从Laravel实例向Conveyor WebSocket服务器进行广播。要了解如何使用Laravel进行广播,请访问Broadcasting

步骤 9:安装Conveyor JS客户端

npm install socket-conveyor-client

重要:不要忘记运行npm run build

将此添加到Laravel应用的bootstrap.js文件中,以便Conveyor客户端全局可用

import Conveyor from "socket-conveyor-client";

window.Conveyor = Conveyor;

请记住运行npm installnpm run devnpm run prod来编译资源。

信息:如果您想向Conveyor WebSocket服务器发送一次性消息,您可以像以下这样分发事件

<?php

namespace App\Events;

use Illuminate\Broadcasting\InteractsWithBroadcasting;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

class TestEvent implements ShouldBroadcastNow
{
    use InteractsWithBroadcasting;

    public function __construct(
        public string $message,
        public string $channel,
    ) {
        $this->broadcastVia('conveyor');
    }

    public function broadcastOn(): array
    {
        return [
            new PrivateChannel($this->channel),
        ];
    }
}
event(new App\Events\TestEvent( message: 'my message', channel: 'my-channel'));

重要:请注意,我们使用的是ShouldBroadcastNow而不是ShouldBroadcast。Conveyor不需要排队,这种方式更快。如果您愿意,您仍然可以使用队列。

在此时在具有授权的视图中使用示例

<html>
<head>
    <title>WS Client</title>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>

<textarea id="msg"></textarea>
<button id="btn-base">Base</button>
<button id="btn-broadcast">Broadcast</button>
<ul id="output"></ul>

<script type="text/javascript">
    // page elements
    const msg = document.getElementById('msg')
    const btnBase = document.getElementById('btn-base')
    const btnBroadcast = document.getElementById('btn-broadcast')
    const output = document.getElementById('output')

    const connect = (token) => {
        let conveyor = new window.Conveyor({
            protocol: '{{ $protocol }}',
            uri: '{{ $uri }}',
            port: {{ $wsPort }},
            channel: '{{ $channel }}',
            query: '?token=' + token,
            onMessage: (e) => output.innerHTML = e,
            onReady: () => {
                btnBase.addEventListener('click', () => conveyor.send(msg.value))
                btnBroadcast.addEventListener('click', () => conveyor.send(msg.value, 'broadcast-action'))
            },
        });
    };

    const  getAuth = (callback) => {
        fetch('/broadcasting/auth?channel_name={{ $channel }}', {
            headers: {
                'Accept': 'application/json',
            },
        })
            .then(response => response.json())
            .then(data => callback(data.auth))
            .catch(error => console.error(error));
    }

    document.addEventListener("DOMContentLoaded", () => getAuth(connect));
</script>
</body>
</html>

然后,在您的routes/web.php文件中添加此视图的路由

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;

Route::get('/ws-client', function () {
    Auth::loginUsingId(1); // here we authorize for the sake of the example.

    $protocol = config('jacked-server.ssl-enabled') ? 'wss' : 'ws';
    $port = config('jacked-server.ssl-enabled') ? config('jacked-server.ssl-port') : config('jacked-server.port');

    return view('ws-client', [
        'protocol' => $protocol,
        'uri' => '127.0.0.1',
        'wsPort' => $port,
        'channel' => 'private-my-channel',
    ]);
});