thinkphp结合workerman和gateway实现数据同步
0x10安装扩展
composer require topthink/think-worker=2.0.*
composer require workerman/gatewayclient
此安装仅针对5.1,其他版本根据官方要求安装。client仅针对3.0.8以上,具体看GitHub
0x20服务端Gateway
0x21config/worker_gateway.php
<?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>
// +----------------------------------------------------------------------
// +----------------------------------------------------------------------
// | Workerman设置 仅对 php think worker:gateway 指令有效
// +----------------------------------------------------------------------
return [
// BusinsessWorker配置
'businessWorker' => [
'name' => 'BusinessWorker',
'count' => 1,
'eventHandler' => '\app\http\Gateway',
],
];
0x22 application/http/Gateway.php
<?php
namespace app\http;
use GatewayWorker\Lib\Gateway as Way;
class GateWay
{
public static function onWebSocketConnect($id, $data)
{
dump('设备连接,ID:' . $id);
Way::bindUid($id, '1');
}
public static function onMessage($client_id, $data)
{
Way::sendToClient($client_id, '服务端消息');
}
}
0x23 向客户端发送消息
//use GatewayClient\Gateway;
$post = request()->post();
Gateway::$registerAddress = '127.0.0.1:1236';
// 向任意uid的网站页面发送数据
Gateway::sendToUid('1', json_encode($post));
dump($post);
0x30客户端代码
客户端需要用到command,即thinkphp命令行
protected function execute(Input $input, Output $output)
{
//忽略....
$a = new Worker();
$a->onWorkerStart = function ($work) {
$con = new AsyncTcpConnection('ws://192.168.25.149:2346');//服务端地址
$con->onConnect = function (AsyncTcpConnection $con) {
// 连接成功的事件
};
$con->onMessage = function (AsyncTcpConnection $con, $data) {
dump($data);//来自服务端的消息
};
$con->connect();
};
Worker::runAll();
}