laravel广播系统使用redis作为驱动,队列、echo-server 都正常,但前端就是接收不到发来的数据?

我用的环境是:
windows7
php 7.4.3
nginx 1.16.1
redis 3.0.504
mysql 5.7
laravel 8.12
1、把localhost本地域名解析的到laravel的public目录下,并该域名下的nginx做了伪静态

location / {  
    try_files $uri $uri/ /index.php$is_args$query_string;  
}  

2、把config\app.php文件的 App\Providers\BroadcastServiceProvider::class的一行取消注释


        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,

3、安装广播系统需要的依赖:

composer require predis/predis
npm install
npm install -g laravel-echo-server
npm install --save laravel-echo
npm install --save socket.io-client

4、使用php artisan make:event News 创建广播事件 实现 ShouldBroadcast

<?php

namespace App\Events;

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

class News implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message ; 
    /**
     * Create a new event instance.
     *
     * @return void
     */
    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 PrivateChannel('channel-name');
        return new Channel('news-test');
    }

    /**
     * 获取广播数据
     *
     * @return array
     */
    public function broadcastWith()
    {
        return ['message' => $this->message];
    }
}

5、在routes\channels.php文件中添加news-test频道:

<?php

use Illuminate\Support\Facades\Broadcast;

/*
|--------------------------------------------------------------------------
| 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('App.Models.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});


Broadcast::channel('news-test', function () {
    return true;
});

6、在routes\console.php文件下添加触发App\Eevnt\News的事件bignews:

<?php

use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;

/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/

Artisan::command('inspire', function () {
    $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');


Artisan::command('bignews', function () {
    broadcast(new \App\Events\News(date('Y-m-d H:i:s') . 'news socket message'));
    $this->comment('message is send');
});

7、在.env文件中设置的广播 、队列、redis的配置:

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

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_PREFIX=null

8、在resources\js\bootstrap.js 追加laravel-echosocket.io-client代码:

window._ = require('lodash');

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo';

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: process.env.MIX_PUSHER_APP_KEY,
//     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//     forceTLS: true
// });

/**
 * 新添加代码
 */
import Echo from 'laravel-echo';
window.io = require('socket.io-client');
window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001',
});

9、在resources\view目录下增加broadcast.blade.php广播测试页面:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>广播测试页面</title>
    <link href="{{ mix('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div class="content" id="app">
    Broadcast Service
</div>
{{--<script src="{{ asset('./../resources/assets/js/app.js') }}"></script>--}}
<script src="{{ mix('js/app.js') }}"></script>
<script>
    Echo.channel('news-test')
        .listen('News', (e) => {
            console.log(e.message );
            console.log(e);
        });
</script>
</body>
</html>

9、routes\web.php添加“广播测试页面”路由broadcast

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

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

11、使用命令行编译打包前端文件:

npm run dev

12、使用laravel-echo-server init初始化当前项目的laravel-echo-server.json文件:

>laravel-echo-server init
? Do you want to run this server in development mode? Yes
? Which port would you like to serve from? 6001
? Which database would you like to use to store presence channel members? redis
? Enter the host of your Laravel authentication server. http://localhost
? Will you be serving on http or https? http
? Do you want to generate a client ID/Key for HTTP API? No
? Do you want to setup cross domain access to the API? No
? What do you want this config to be saved as? laravel-echo-server.json
Configuration file saved. Run laravel-echo-server start to run server.

13、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": ""
    }
}

14、启动laravel-echo-server服务:

laravel-echo-server start

laravel-echo-server服务已启动如下显示:

>laravel-echo-server start

L A R A V E L  E C H O  S E R V E R

version 1.6.2

⚠ Starting server in DEV mode...

✔  Running at localhost on port 6001
✔  Channels are ready.
✔  Listening for http events...
✔  Listening for redis events...

Server ready!

[ioredis] Unhandled error event: Error: read ECONNRESET
    at TCP.onStreamRead (internal/stream_base_commons.js:205:27)

15、再开启一个命令行终端启动消息队列服务:

php artisan queue:work

16、浏览器打开”广播测试页面” ,http://localhost/broadcast,显示如下:

17、再开启一个命令行终端 使用命令行触发频道事件:

php artisan bignews

显示如下:
laravel广播

18、为什么前端没有获取的数据,请各位高手解答一下,哪里出了问题?

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

更换socket.io-client版本,执行npm uninstall socket.io-clientnpm install socket.io-client@2.3.0两命令已可以正常使用,谢谢大神

file

3年前 评论
wen2019 2年前
讨论数量: 5

[ioredis] Unhandled error event: Error: read ECONNRESET at TCP.onStreamRead (internal/stream_base_commons.js:205:27)

是 Redis 连接不上导致的问题么?

3年前 评论
Cruseo (楼主) 3年前

https://learnku.com/laravel/t/52388

3年前 评论
leslieeilsel 3年前

Laravel 的广播系统,与 echo-server 服务是通过 Redis 的订阅与发布 实现通信的。建议先确认广播数据是否已推到 Redis 中,再确认 echo-server 是否能连通 Redis

看上面的 laravel-echo-server.json 文件好像没有配置 redis 相关信息,可以配置下再尝试:

...
"databaseConfig": {
    "redis": {
        "port": "6379",
        "host": "xxxx",
        "password": "xxxx"
    },
    "sqlite": {
          "databasePath": "/database/laravel-echo-server.sqlite"
     }
 },
...
3年前 评论
Cruseo (楼主) 3年前

broadcast.blade.php 加入这一行

<script src="//{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>
3年前 评论

更换socket.io-client版本,执行npm uninstall socket.io-clientnpm install socket.io-client@2.3.0两命令已可以正常使用,谢谢大神

file

3年前 评论
wen2019 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!