websocket Laravel 8中的Web Socket

fdbelqdn  于 2024-01-08  发布在  其他
关注(0)|答案(1)|浏览(166)

我正在尝试使用Web Socket.
这是我的App\Events\TestEvent.php

<?php

namespace App\Events;

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

use App\Models\User;

class TestEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */

    public $user;
    public $d;

    public function __construct()
    {
        $this->user = 1;
        $this->d = User::find($this->user);
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        // return new PrivateChannel('channel-name');
        return ['testevent'];
    }

    public function broadcastWith()
    {
        return ['data' => 1];
    }
}

字符串
这是我的应用程序测试

<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

use App\Events\TestEvent;
use App\Models\User;

class TestListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(TestEvent $event)
    {
        $userID = $event->user;
        $user_details = User::find($userID);
    }
}


当点击URL时,我正在广播此事件,

broadcast(new TestEvent());


我在这里展示的是前端

<script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
    <script type="text/javascript">

        window.Echo.channel('testevent').listen('TestEvent', function (e) {
            console.log('Event received:');
            // $('#gg').text(data);
        });
        
    </script>


当我点击URL事件正在注册的Web Socket和连接正在进行,并在每30秒自动获取数据.但在响应的Web Socket我期待的数据,但数据键是空的。响应是来作为
“{event:“pusher:ping”,data:{}} data:{} event:“pusher:ping”“

ryhaxcpt

ryhaxcpt1#

像这样试试。

let channel = window.Echo.join("testevent");
  channel.listen("TestEvent", ({ data }) => {
        console.log(data);
  });

字符串
在TestEvent类中,添加如下内容:

public function broadcastOn()
 {
    return new PresenceChannel('testevent');
 }


像这样的广播。

broadcast(new TestEvent())->toOthers();

相关问题