Laravel Echo不收听公共频道的事件吗?

时间:2020-07-14 12:55:40

标签: javascript laravel websocket laravel-echo

我正在使用Laravel Websockets软件包。服务器端的一切看起来都很不错,但是Laravel Echo没有监听事件。 MySocketEvent.php:

<?php

namespace App\Events;

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

class MySocketEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $data;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        //
        $this->data=$data;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('DemoChannel.1');
    }

    public function broadcastAs()
{
    return 'testing';
}
}

Web.php

Route::get('tests',function(){

    $arr=['some'=>'some'];

    broadcast(new \App\Events\MySocketEvent($arr));
    return view('hi');


});

Bootstrap.js

import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
   

    broadcaster: 'pusher',
    //key: process.env.MIX_PUSHER_APP_KEY,
    key: 'my-key',
    wsHost: window.location.hostname,
    wsPort: 6001,
    wssPort: 6001,

    disableStats: true,
    cluster: 'ap2',
    //cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    //encrypted: true
});


//subscribe-for-the-test-demo-channel-and-listen

window.Echo.channel('DemoChannel.1')
    .listen('.testing', (e) => {
        console.log("Received Data: ");
        console.log(e);
    });


我看到使用php artisan WebSockets:serve从服务器发送的数据,但是Laravel Echo没有监听。请帮忙。我100%肯定Laravel Echo有问题。

2 个答案:

答案 0 :(得分:0)

“测试”之前的“点”

广播为“ 测试

收听“ .testing

替换此

window.Echo.channel('DemoChannel.1')
.listen('.testing', (e) => {
    console.log("Received Data: ");
    console.log(e);
});

对此

window.Echo.channel('DemoChannel.1')
.listen('testing', (e) => {
    console.log("Received Data: ");
    console.log(e);
});

更新

将此行添加到事件文件中

use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

替换此

class MySocketEvent implements ShouldBroadcast

对此

class MySocketEvent implements ShouldBroadcastNow

答案 1 :(得分:0)

我可以通过将pusher降级到4.4.0来使Echo正常工作

npm install pusher-js@4.4.0