【开发环境】
PHP:7.4
Laravel:5.8
redis:6.2.2
配置过程
1、修改.env文件
BROADCAST_DRIVER=redis
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
2、安装predis/predis
composer require predis/predis
3、取消config/app.php下BroadcastServiceProvider的注释
App\Providers\BroadcastServiceProvider::class,
4、全局安装laravel-echo-server
npm install -g laravel-echo-server
5、初始化 Socket 服务
laravel-echo-server init
后续可以在下图文件中修改
6、启动服务
laravel-echo-server start
正常情况下应该是四个都显示,如果没有全显示可以看看是不是redis出了问题,比如没启动啥的
7、安装 Socket.io 客户端和 Laravel-Echo 包
npm install --save socket.io-client@2.0.1
npm install --save laravel-echo
npm install
8、在resources/assets/js/bootstrap.js中加入以下代码
import Echo from 'laravel-echo'
window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
9、执行npm run dev命令
10、在前端代码中加入以下内容
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="{{ asset('js/app.js') }}"></script>
</head>
<body>
<script>
window.Echo.channel('laravel_database_news')
.listen('PushMsgEvent', (e) => {
console.log(e);
});
</script>
</body>
11、后台创建一个事件
php artisan make:event PushMsgEvent
首先实现ShouldBroadcast接口;其次修改broadcastOn()方法;最后添加broadcastWith()方法。
<?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 PushMsgEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('news');
}
public function broadcastWith()
{
return [
'data' => 'Hello World!'
];
}
}
12、创建一个command
php artisan make:command PushMsg
<?php
namespace App\Console\Commands;
use App\Events\PushMsgEvent;
use Illuminate\Console\Command;
class PushMsg extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'push:msg';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Push a message for broadcast';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
broadcast(new PushMsgEvent);
}
}
执行过程
1、开启laravel-echo-server
laravel-echo-server start
2、开启queue
php artisan queue:work
3、执行PushMsg命令
php artisan push:msg
结果
注意:
1、要把服务器的6001端口开放;
2、socket.io的版本必须是2.x