config/app.php 取消以下代码的注释
App\Providers\BroadcastServiceProvider::class,
.env配置
BROADCAST_DRIVER=redis QUEUE_CONNECTION=redis
database.php类phpredis 改为 predis
如果你使用 Redis 广播器,请通过 PECL 安装 redis 扩展和安装 Predis 库:
composer require predis/predis
引入 Socket.IO JavaScript 客户端库
npm install --save socket.io-client@2.*
客户端封装
npm install --save laravel-echo
服务端
npm install -g laravel-echo-server
安装依赖
npm install
resources/js/bootstrap.js内实例化 Echo 时指定 socket.io 连接器和 host,添加以下代码:
import Echo from "laravel-echo"
window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});resources/js/bootstrap.js内监听事件广播
window.Echo.channel(`laravel_database_push`)
.listen('.push.message', (e) => {
console.log(e);
});生成事件
php artisan make:event PushMsgEvent
代码
<?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 PushMsgEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $eventName;
public $msg = '';
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($eventName,$msg)
{
$this->eventName = $eventName;
$this->msg = $msg;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel($this->eventName);
}
// 自定义事件名称
public function broadcastAs()
{
return 'push.message';
}
}web.php配置路由
Route::get('/event', function () {
event(new \App\Events\PushMsgEvent('push','这是一条消息'));
});在laravel初始化welcome.balde.php模板head之间添加
<script src="js/app.js"></script>
初始化服务端
laravel-echo-server init

启动redis
执行下载的文件 redis-server.exe
执行package.json中的script脚本
npm run dev
启动队列处理器
php artisan queue:work
启动服务端
laravel-echo-server start
最后1、访问laravel项目首页也就是welcome.blade.php页面;2、访问路由event;3、回到首页查看console输出。