laravel-echo如何工作pusher和反应js?

时间:2019-06-16 01:36:44

标签: reactjs laravel pusher

我已经使用laravel通行证创建了REST API,并将其放置在我的子域(即“ api.abc.com”)中。我有一个连接它的react js应用程序。现在,为了添加实时消息传递,我使用了“推动器”和“ laravel回声”。

React应用程序可以成功连接到Pusher,每次在调试控制台上都可以看到。在我发送消息的地方,它也存储在数据库和推送程序中。但是没有触发相应的laravel回声通道侦听器。我已经尝试了所有变体,但无法使其正常工作。

REST API放置在服务器上,React APP当前在本地托管。这就是为什么我将“ encrypted”设置为“ false”的原因。

APP //事件// 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));

config // 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',
        ],

    ],

];

routes // channels.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 APP

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);
        });

但是我从来没有看到任何console.log数据。

2 个答案:

答案 0 :(得分:1)

ShouldBroadcast更改为ShouldBroadcastNow

您的邮件正在排队。

答案 1 :(得分:0)

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

来跟踪正在调度的事件