laravel echo server with socket io and redis

2.6k views Asked by At

I try to create real time app with laravel-echo server and socket.io, but client doesn't became messages

Here is my code:

.env

BROADCAST_DRIVER=redis
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=redis

config/queue.php

 'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
        'queue' => 'default',
        'retry_after' => 90,
 ],

config/database.php

'redis' => [

    'retry_after' => 90,
    'default' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', 6379),
        'database' => 0,
    ],

],

routes/channels.php

Broadcast::channel('messages', function() {
    return true;
}); 

src/echo.js

import Echo from "laravel-echo"

window.Echo = new Echo({
   broadcaster: 'socket.io',
   host:'http://localhost:6001'
});

window.Echo.channel('messages')
  .listen('.newMessage', (message) => {
    debugger;
});

Events/MessagePosted.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 MessagePosted implements ShouldBroadcast {

 use Dispatchable, InteractsWithSockets, SerializesModels;

protected $message;

public function __construct($message)
{
    $this->message = $message;
}

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

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

public function broadcastOn()
{
    return new Channel('messages');
}
}

MessageController.php

public function post(Request $request)
{
    event(new MessagePosted($request->get('message')));
} 

Redis server is installed, in redis-cli PING command return PONG. I use php artisan queue:work redis, but after sending message from client, nothing is displaying into queue... Clients connect to the laravel-echo-server, its return : [14:04:17] - C3c8UUnTn9dvOPc9AAAA joined channel: messages. And POST request is processed

2

There are 2 answers

0
H.Rad On

first of all you should run queue server to handle queued events because you implement ShouldBroadcast, so run php artisan queue:listen note that add REDIS_CLIENT=predis & REDIS_PREFIX= to your .env file and make sure you installed predis/predis package. and change event(new MessagePosted($request->get('message'))) to MessagePosted::dispatch($request->get('message'))

0
Ivan Stanisavljevic On

You are listening to the .newMessage but sending .App.Events.MessagePosted instead.

Change the listen function param in your JS:

window.Echo.channel('messages')
  .listen('.App.Events.MessagePosted', (message) => {
  debugger;
});