PHP code example of sparkinzy / dcat-websocket

1. Go to this page and download the library: Download sparkinzy/dcat-websocket library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sparkinzy / dcat-websocket example snippets


class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
//        Broadcast::routes();

        


Broadcast::channel('room', function () {
    return true;
});

'connections' => [
    'pusher' => [
        'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'useTLS' => true,
                // 拦截 pusher 的广播后,转发到目标 ip
                'host' => '127.0.0.1',
                // 转发的端口,就是我们之前在 .env 文件中配置的 2022 端口
                'port' => env('LARAVEL_WEBSOCKETS_PORT', 2022),
            ],
    ];
];

$user_id = Admin::user()->id ?? 0;
Admin::script(<<<JS
// 公共渠道
DcatEcho.channel('task')
.listen('TaskSuccessEvent',function(e){
    console.log(e)
    $('#task-'+e.task_id).html('发布成功');
});
// 私有渠道
DcatEcho.private('room.{$user_id}')
  .listen('TaskErrorEvent',(e)=>{
      console.log(e)
  })

JS
);

bash
# 依赖以下扩展包
composer websockets
# 发布相关文件 如 config/websockets.php
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider"
bash
php artisan websockets:serve --port=2022