pelim / laravel-zmq

laravel zmq broadcast driver
21 stars 8 forks source link

Broadcast event doesn't reach Frontend #5

Open tonysm opened 6 years ago

tonysm commented 6 years ago

Hi there. Thanks for the effort on this package. I'm having an issue, don't know if you can help me here. I'm trying to use this package with askedio/laravel-ratchet and simonhamp/echo to broadcast events to the frontend, but it's not reaching it.

Steps I've followed:

Install askedio/laravel-ratchet:

Publish configs using php artisan vendor:publish --provider="Askedio\LaravelRatchet\Providers\LaravelRatchetServiceProvider"

My local configs are:

config/ratchet.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Laravel Ratchet Configuration
    |--------------------------------------------------------------------------
    |
    | Here you can define the default settings for Laravel Ratchet.
    |
    */

    'class'           => \Askedio\LaravelRatchet\Examples\Pusher::class,
    'host'            => '0.0.0.0',
    'port'            => '8080',
    'connectionLimit' => false,
    'throttle'        => [
        'onOpen'    => '5000:1',
        'onMessage' => '20000:1',
     ],
    'abortOnMessageThrottle' => false,
    'blackList'              => [],
    'zmq'                    => [
        'host'   => '127.0.0.1',
        'port'   => 5555,
        'method' => \ZMQ::SOCKET_PULL,
    ],
];

I start the server using the ZMQ option: php artisan ratchet:serve --driver=WsServer -z, I see this output:

Starting WsServer server on: 0.0.0.0:8080
Starting ZMQ listener on: 127.0.0.1:5555

Install the simonhamp/echo package

*resources/assets/js/bootstrap.js

-import Echo from 'laravel-echo'
-
-window.Pusher = require('pusher-js');
+import Echo from 'laravel-echo-ratchet'

 window.Echo = new Echo({
-    broadcaster: 'pusher',
-    key: process.env.MIX_PUSHER_APP_KEY,
-    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
-    encrypted: true,
+    broadcaster: 'ratchet',
+    host: 'ws://localhost:8080',
 });

I don't see any issue in the console. And the output in the terminal makes me think the connection works:

Starting WsServer server on: 0.0.0.0:8080
Starting ZMQ listener on: 127.0.0.1:5555
Connected: 397
1 connection
Message from 397: {"event":"subscribe","message":{"channel":"messages","auth":{"headers":{"X-CSRF-TOKEN":"d2iq1PclvWSZtegEv46YdAxJr5ut3yVsRNGpdvVJ"}}}}

I'm adding the zmq connection to the broadcasting config and setting the env BROADCAST_DRIVER=zmq, as described in the docs.

The Problem

I have an event:

app/Events/NewMessage.php

<?php

namespace App\Events;

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

class NewMessage implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    /**
     * @var string
     */
    public $message;

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

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

And a command to feed in some messages:

app/Console/SendMessages.php

<?php

namespace App\Console\Commands;

use Faker\Factory;
use App\Events\NewMessage;
use Illuminate\Console\Command;

class SendMessages extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:messages {--amount=2}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sends fake messages';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $faker = Factory::create();
        $amount = $this->option('amount');

        foreach (range(1, $amount) as $i) {
            broadcast(new NewMessage(
                $faker->sentence()
            ));
        }
    }
}

and I can call it with php artisan app:messages. I see no error, which means it might be working.

I also have the ExampleComponent rendering in the welcome.blade.php :

resources/views/welcome.blade.php

@extends('layouts.app')

@section('content')
    <example-component></example-component>
@endsection

The app layout comes from Laravel's auth scaffolding, which includes the compiled JS and CSS files. The example component looks like this:

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card card-default">
                    <div class="card-header">Example Component</div>

                    <div class="card-body">
                        <ul class="list-group" v-if="messages.length">
                            <li class="list-group-item" v-for="message in messages">{{ message }}</li>
                        </ul>
                        <p v-if="messages.length === 0">No messages yet</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data () {
            return {
                messages: []
            };
        },
        mounted() {
            Echo.channel('messages')
                .listen('NewMessage', (e) => {
                    this.messages.push(e.message);
                });
        }
    }
</script>

I see no error. I tried to debug, but everything looks fine. The config/zmq.php file has this:

<?php

return [
    'default' => 'publish',

    'connections' => [

        'publish' => [
            'dsn'       => 'tcp://127.0.0.1:5555',
            'method'    => \ZMQ::SOCKET_PUB,
        ],

        'subscribe' => [
            'dsn'    => 'tcp://0.0.0.0:5555',
            'method'    => \ZMQ::SOCKET_SUB,
        ],

    ]
];

The logs say the message is being sent, but nothing reaches the front-end.

storage/logs/laravel.log

[2018-07-21 22:38:00] local.DEBUG: zmq.publish {"channel":"messages","payload":"{\"event\":\"App\\\\Events\\\\NewMessage\",\"payload\":{\"message\":\"Molestiae tempore dolorem doloremque dolores minus.\",\"socket\":null}}"} 
[2018-07-21 22:38:00] local.DEBUG: zmq.publish {"channel":"messages","payload":"{\"event\":\"App\\\\Events\\\\NewMessage\",\"payload\":{\"message\":\"Ipsum corporis a labore et ex quis.\",\"socket\":null}}"}

Am I doing anything wrong here?

Again, thanks for the effort! Sorry to bother!

tonysm commented 6 years ago

I've created a demo repository so you can reproduce it, if you want to: https://github.com/tonysm/laravel-ratchet-zmq-echo

maxalmonte14 commented 5 years ago

Hey @tonysm, I was trying to make your little app work, I couldn't, but have you noticed that the log is saving the socket property as null?

In your example, and my environment log there is the following \"socket\":null

Taking into account that we're interacting with a socket server, should this be null or not?

Just trying to find a possible source of errors.

SteaveAshmore commented 5 years ago

i am also facing same problem, any solution?

ghost commented 3 years ago

Yeah I'm having this issue as well .. maybe time to switch to a different package.

Athov commented 3 years ago

In the config changing publish method from \ZMQ::SOCKET_PUB to \ZMQ::SOCKET_PUSH made it work.