1
votes

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

1
Did you get this working?Cato Minor
@CatoMinor yes, I don't know why, but after I created new laravel app its finally working..bitbucket.org/karpalex/student-room here you can see working laravel with socket example, not sure about other logic, but larave + socket io works perfectAlexander Karp
Thanks! Maybe i'll need to create a new laravel project too. :|Cato Minor

1 Answers

1
votes

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