arnislielturks/socketio-laravel-broadcaster

Socket.io Laravel 广播器

0.3.1 2020-05-14 08:03 UTC

This package is auto-updated.

Last update: 2024-09-22 16:56:00 UTC


README

此包允许将 Laravel 事件直接发送到 socket.io 服务器

安装

  1. 通过 composer 安装包
composer require arnislielturks/socketio-laravel-broadcaster
  1. 在 config/app.php 中注册提供者
// 'providers' => [
   ...
   
   ArnisLielturks\SocketIOBroadcaster\SocketIOBRoadcasterProvider::class
// ];
  1. 添加配置文件 (config/socketio.php),内容如下。应指向 socket.io 服务
return [
    'server' => 'http://127.0.0.1:3000'
];
  1. 将广播驱动程序更改为 (config/broadcasting.php) 中的 socketio
default' => env('BROADCAST_DRIVER', 'socketio'),

或者在此 .env 文件中设置此值

BROADCAST_DRIVER=socketio
  1. 更新 config/broadcasting.php
'connections' => [
        ...
        
        'socketio' => [
            'driver' => 'socketio'
        ]

    ],
  1. 创建一个事件,通过 Socket.io 服务发送广播
class TestEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    //All public attributes will be sent with the message
    public $id;
    public $event = 'test_event';

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

    public function broadcastOn()
    {
        //List of channels where this event should be sent
        return ['/test_event'];
    }

}
  1. 通过控制器发送事件
class TestController extends Controller
{
    public function test() {
        event(new TestEvent());
        return view('main');
    }
}
  1. 发送到 socketio 的消息将如下所示
{ 
  id: 123,
  event: 'test_event'
}

就是这样!