【发布时间】:2020-11-03 19:43:00
【问题描述】:
我正在使用 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。
【问题讨论】:
标签: javascript laravel websocket laravel-echo