简单的广播事件实现

安装Laravel-echo-server
1
npm install -g laravel-echo-server
配置Laravel-echo-server
1
2
3
4
5
6
7
8
9
$ 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://echo.test
? 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
Configuration file saved. Run laravel-echo-server start to run server.
启动Laravel-echo-server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ laravel-echo-server start                                              

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

version 1.4.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!
Laravel项目添加redis
1
composer require predis/predis
.env中修改广播 缓存 队列为redis配置
1
2
3
BROADCAST_DRIVER=redis
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
安装所需的依赖包
1
2
3
$ npm install --save socket.io-client
$ npm install --save laravel-echo
$ npm install
前端配置 编辑 project/resources/js/bootstrap.js
1
2
3
4
5
6
7
import Echo from 'laravel-echo'

window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
前端编译
1
$ npm run dev
创建Event
1
2
$ php artisan make:event DevEvent                                      
Event created successfully.
编辑 echo/app/Events/DevEvent.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?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;
// 应用ShouldBroadcast接口
class DevEvent 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()
{
//默认为PrivateChannel私有频道,修改为Channel
return new Channel('dev-channel');
}
}
为了测试输出,定义一个 broadcastWith() 方法
1
2
3
4
5
6
7
8
9
10
11
/**
* @return array
* 消息输出
*/
public function broadcastWith()
{
return [
'status' => 'success',
'message' => 'test message'
];
}
再创建一条command测试广播动作 project/routes/console.php
1
2
3
4
5
6
7
8
//测试广播发送
Artisan::command('Test:Broads',function (){
broadcast(new \App\Events\DevEvent());
})->describe('test broads');
//查看artisan命令列表
$ php artisan
Test
Test:Broads test broads
OK,接着到前台模板 project/resources/views/welcome.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="csrf-token" content="{{csrf_token()}}">
<title>test page</title>
</head>
<body>
<div id="app">
test page
</div>
</body>
<script src="{{ asset('js/app.js') }}"></script>
<script>
// 前面event创建好的channel名称
window.Echo.channel('dev-channel')
// 监听 DevEvent 这个事件
.listen('DevEvent', (e) => {
console.log(e);
alert('状态:'+e.status+' '+'消息:'+e.message);
});
</script>
</html>
查看连接

51926569.png

保持监听
1
$  php artisan queue:listen --tries=1
通过命令发送广播
1
php artisan Test:Broads
监听列表
1
2
3
$ php artisan queue:listen --tries=1                                     
[2018-10-19 06:47:16][4NMQFjSO4kN8shfWX5UNTr3Ss0QJnImb] Processing: App\Events\DevEvent
[2018-10-19 06:47:16][4NMQFjSO4kN8shfWX5UNTr3Ss0QJnImb] Processed: App\Events\DevEvent
Echo 列表
1
2
Channel: channel-name
Event: App\Events\DevEvent
页面响应

QQ20181019-145324@2x.png

简单的广播,到此算是OK了

现在有个场景,用户购买了某个商品,购买成功后,马上给用户发送一个私有频道的广播通知这个在下一篇私有频道中实现