TP6安装GatewayWorker

首先根据thinkphp官网手册安装依赖

1
composer require topthink/think-worker

1、自定义你的事件类文件
在你的应用app目录下新建一个http目录,目录下新建一个Events.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace app\http;

use GatewayWorker\Lib\Gateway;
use Workerman\Worker;
use think\worker\Application;

/**
* Worker 命令行服务类
*/
class Events
{
/**
* onWorkerStart 事件回调
* 当businessWorker进程启动时触发。每个进程生命周期内都只会触发一次
*
* @access public
* @param \Workerman\Worker $businessWorker
* @return void
*/
public static function onWorkerStart(Worker $businessWorker)
{
$app = new Application;
$app->initialize();
}

/**
* onConnect 事件回调
* 当客户端连接上gateway进程时(TCP三次握手完毕时)触发
*
* @access public
* @param int $client_id
* @return void
*/
public static function onConnect($client_id)
{
Gateway::sendToCurrentClient("Your client_id is: $client_id");
}

/**
* onWebSocketConnect 事件回调
* 当客户端连接上gateway完成websocket握手时触发
*
* @param integer $client_id 断开连接的客户端client_id
* @param mixed $data
* @return void
*/
public static function onWebSocketConnect($client_id, $data)
{
var_export($data);
}

/**
* onMessage 事件回调
* 当客户端发来数据(Gateway进程收到数据)后触发
*
* @access public
* @param int $client_id
* @param mixed $data
* @return void
*/
public static function onMessage($client_id, $data)
{
Gateway::sendToAll($data);
}

/**
* onClose 事件回调 当用户断开连接时触发的方法
*
* @param integer $client_id 断开连接的客户端client_id
* @return void
*/
public static function onClose($client_id)
{
GateWay::sendToAll("client[$client_id] logout\n");
}

/**
* onWorkerStop 事件回调
* 当businessWorker进程退出时触发。每个进程生命周期内都只会触发一次。
*
* @param \Workerman\Worker $businessWorker
* @return void
*/
public static function onWorkerStop(Worker $businessWorker)
{
echo "WorkerStop\n";
}
}

业务开发只需要关注 Applications/项目/Events.php一个文件即可。

2.修改config目录下gateway_worker.php文件如下

1
2
3
4
5
6
// BusinsessWorker配置
'businessWorker' => [
'name' => 'BusinessWorker',
'count' => 1,
'eventHandler' => 'app\http\Events',
],

最后执行启动命令完成~~~

1
php think worker:gateway