【发布时间】:2020-09-19 07:44:34
【问题描述】:
编辑:忘记添加 bootstrap.js
我正在尝试使用 Pusher 和 Laravel-Echo 设置 websocket,但我遇到了一个奇怪的错误。我可以看到我的事件在 Pusher 调试器控制台上被触发,但我没有在我的前端收到事件。这是我设置 Pusher 的代码:
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,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true,
});
broadcast.php
'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'),
'encrypted' => true
],
],
app.php
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
OptionChange.php(这是我正在监听的事件)
<?php
namespace App\Events;
use App\ItemInstance;
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 OptionChange implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $instance;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(ItemInstance $instance)
{
$this->instance = $instance;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('itemInstance' . $this->instance->id);
}
// return this info in Pusher
public function broadcastWith() {
return [
'id' => $this->instance->id,
'answer' => $this->instance->answer,
'question_number' => $this->instance->question_number
];
}
}
React Code(我正在监听我的事件)
// set up channel listener for live updates
componentDidMount() {
const { started, studentId } = this.state
if (!started) {
window.Echo.channel('studentStartedTest' + studentId)
.listen('StartTest', (didStart) => {
console.log('startTest')
if (didStart) {
this.setState({ started: true })
}
})
} else {
// window.Echo.leaveChannel('studentStartedTest' + studentId)
window.Echo.channel('itemInstance' + this.props.id)
.listen('OptionChange', (instance) => {
console.log('change')
this.setState({ answer: instance.answer })
})
}
}
如您所见,每当我的事件触发时,我都会尝试使用console.log。不幸的是,console.log 永远不会运行。
我也尝试将 implements ShouldBroadcast 更改为 implements ShouldBroadcastNow 但这并没有改变任何东西
【问题讨论】:
标签: reactjs websocket pusher laravel-echo