GatewayWorker实现了对workman的封装,可以用来快速开发websocket
安装
1.安装TP6
$ composer create-project topthink/think GatewayWorker
$ cd GatewayWorker
2.引入GatewayWorker
think-worker扩展包同时包含了workerman和GatewayWorker
$ composer require topthink/think-worker
3.启动GatewayWorker
$ php think worker:gateway

4.ws连接测试

开发
1.创建事件处理类
- 新建控制器 - \app\controller\GatewayWorker.php
- 继承 - \think\worker\Events
- 根据需求重写事件监听方法 - 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
 namespace app\controller;
 use GatewayWorker\Lib\Gateway;
 use think\worker\Application;
 use think\worker\Events;
 use Workerman\Worker;
 /**
 * GatewayWorker事件监听类
 */
 class GatewayWorker extends 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";
 }
 }
2.修改默认事件监听类配置
修改config/gateway_worker.php
| 1 | 'eventHandler' => '\app\controller\GatewayWorker' | 
- 本文作者: 小蜗牛
- 本文链接: https://vitaminvi.github.io/2020/07/23/ThinkPHP6对接GatewayWorker开发WebSocket/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!
