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-echo
和socket.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
显示如下:
18、为什么前端没有获取的数据,请各位高手解答一下,哪里出了问题?
推荐文章: