提问者:小点点

laravel echo如何推动和反应js?


我用LaravelPassport创建了RESTAPI,并将它们放在我的子域“api.abc.com”上。我有一个react js应用程序连接到它。现在,为了添加实时消息,我使用了“pusher”和“laravelecho”。

React应用程序可以成功连接到推送器,我每次都可以在调试控制台上看到。在我发送消息的地方,它也被存储在数据库和推送器中。但相应的laravel回波通道侦听器未被触发。我尝试了各种变化,但都没能成功。

RESTAPI放在服务器上,React应用程序当前在本地托管。这就是我将“加密”设置为“假”的原因。

APP//Events//NewMessage


use App\Message;
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 NewMessage implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

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

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('messages.' .  $this->message->conversation_id);
    }

    public function broadcastWith()
    {
        return ["message" => $this->message];
    }

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

在消息存储库函数中注册事件

broadcast(new NewMessage($msg));

配置//broadcasting.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Broadcaster
    |--------------------------------------------------------------------------
    |
    | This option controls the default broadcaster that will be used by the
    | framework when an event needs to be broadcast. You may set this to
    | any of the connections defined in the "connections" array below.
    |
    | Supported: "pusher", "redis", "log", "null"
    |
    */

    'default' => env('BROADCAST_DRIVER', 'null'),

    /*
    |--------------------------------------------------------------------------
    | Broadcast Connections
    |--------------------------------------------------------------------------
    |
    | Here you may define all of the broadcast connections that will be used
    | to broadcast events to other systems or over websockets. Samples of
    | each available type of connection are provided inside this array.
    |
    */

    'connections' => [

        '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' => false,
            ],
        ],

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

        'null' => [
            'driver' => 'null',
        ],

    ],

];

路由//频道。php

<?php

use App\Conversation;

/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/

Broadcast::channel('messages.{id}', function ($user, $id) {
    $con = Conversation::findOrFail($id);
    // return $user->id == $con->user_id || $user->id == $con->shop_owner_id;
    return true;
});

从我的REACT应用程序

import Pusher from "pusher-js";
import Echo from "laravel-echo";
import Cookies from "universal-cookie";

const cookies = new Cookies();

const options = {
    broadcaster: "pusher",
    key: "d4b9af39550bd7832778",
    cluster: "ap2",
    forceTLS: true,
    encrypted: false,
    //authEndpoint is your apiUrl + /broadcasting/auth
    authEndpoint: "https://api.abc.com/broadcasting/auth",
    // As I'm using JWT tokens, I need to manually set up the headers.
    auth: {
        headers: {
            "X-CSRF-TOKEN": csrf_token,
            Authorization: "Bearer " + cookies.get("access_token"),
            Accept: "application/json"
        }
    }
};

const echo = new Echo(options);

在selectConversation函数中,我有以下代码

echo.private("messages." + id).listen(".chat", data => {
            console.log("rumman");
            console.log(data);
        });

我还对以下问题进行了讨论:

echo.private("private-messages." + id).listen(".chat", data => {
            console.log("rumman");
            console.log(data);
        });

但我从来都看不到任何安慰。日志数据。


共2个答案

匿名用户

ShouldBroadcast更改为ShouldBroadcastNow

您的消息正在排队。

匿名用户

Laravel发送广播到队列的事件。因此,您需要进行某种形式的队列驱动程序设置。理想情况下,我将使用Redis作为队列驱动程序,并可以通过运行以下命令跟踪正在调度的事件php artisan queue:work--trys=3

编辑添加:https://laravel.com/docs/7.x/queues#max-job-attempts-and-timeout