L
L
lilzen2021-04-27 19:59:31
Laravel
lilzen, 2021-04-27 19:59:31

How to return response from server in laravel Echo listen on client/server architecture?

Hello, I encountered such a problem, Laravel Echo in a React application on a client / server architecture, does not receive data in listen (i.e., the listen callback function is not called).
on laravel-echo-server and redis on socket.io client and laravel-echo
here is what I used:

EchoExample.js

import React, {useState, useEffect} from "react";
import axios from "axios";
import Echo from "laravel-echo";
window.io = require("socket.io-client");

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ":6001",
});

const instance = axios.create({
    baseURL: "http://" + window.location.hostname + ":8000",
});

export const EchoExample = () => {
    useEffect(() => {
        let channel = window.Echo.channel('chat');
        channel.listen('.Chat', function (e){
            console.log('listen',e)
        })
        console.dir('channel',channel);
    },[])
    const [messages, setMessages] = useState([]);
    //const [text, setText] = useState('');
    const sendMessage = (e) => {
        if (e.keyCode === 13){
            const val = e.target.value;
            setMessages(prev => [...prev, val])
            console.log('send');
            instance.get("messages",{text: val});
            e.target.value = "";
        }
    }
    return (
        <div>
            <input type="text" placeholder={"введите сообщение"} onKeyDown={sendMessage} />
            <div style={{backgroundColor:"black",color: "white"}}>
                {messages.map((item, i) => {
                    return (<div key={i}>{item}<br/></div>);
                })}
            </div>
        </div>
    );
}


routes/web.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/messages', function(Request $request){
    App\Events\Chat::dispatch($request->input('text'));
});

Auth::routes();

Route::get('/home', '[email protected]')->name('home');


App\Events\Chat.php

<?php

namespace App\Events;

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 Chat implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

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

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


.env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:m25beASqWoBAgsyfl+BhRJRRxcZI2apMxJZBaWJKw0k=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

BROADCAST_DRIVER=redis
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"


laravel-echo-server.json

{
  "authHost": "http://localhost",
  "authEndpoint": "/broadcasting/auth",
  "clients": [],
  "database": "redis",
  "databaseConfig": {
    "redis": {},
    "sqlite": {
      "databasePath": "/database/laravel-echo-server.sqlite"
    }
  },
  "devMode": true,
  "host": null,
  "port": "6001",
  "protocol": "http",
  "socketio": {},
  "secureOptions": 67108864,
  "sslCertPath": "",
  "sslKeyPath": "",
  "sslCertChainPath": "",
  "sslPassphrase": "",
  "subscribers": {
    "http": true,
    "redis": true
  },
  "apiOriginAllow": {
    "allowCors": false,
    "allowOrigin": "",
    "allowMethods": "",
    "allowHeaders": ""
  }
}


BroadcastServiceProvider uncommented in config\app.php

in the console I run:
npm start (on the client)
server:
php artisan serve
php artisan queue:work
laravel-echo-server start

when accessing the page and requesting the server, in the consoles I get:
6088423cced12037235661.png
6088424a0f115475468921.png

And in the console in the end it won't come out
channel.listen('.Chat', function (e){
            console.log('listen',e)
        })

608842814c13b664991373.png

Tell me good people, where did I mess up ?! And how can you fix it! I fight 3 days

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question