Browse Source

服务部分基本完成

master
blobt 4 years ago
parent
commit
0c0ec26ecf
  1. 15
      cert/private_key.pem
  2. 6
      cert/pub_key.pem
  3. 4
      composer.json
  4. 414
      composer.lock
  5. 33
      examples/client.php
  6. 2
      examples/index.php
  7. 206
      examples/rsa_test.php
  8. 4
      examples/server.php
  9. 63
      examples/test.php
  10. 242
      src/BaseService.php
  11. 160
      src/Pack.php
  12. 25
      src/Protocol.php
  13. 257
      src/RpcServer.php
  14. 14
      src/Yee.php

15
cert/private_key.pem

@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDsldu7vayXD7RE5HEMsvlz/tkq36gBgY1Yz+R9dkZWNDdQTTFm
O2tWFwBvYRx5Nv/CtR1Nl2+pb/Nd6WrWzs9FR7P84nixA+vfzQjqTIlQViO0vB/a
gWa2nk5N4e0dsQ7kDr3+7/w1DeFsMlRBDvSHMsdmlNSFDFB6+MVrC93dRQIDAQAB
AoGBALhxeJZcIDLA7oSLKEuDOJEjDQGszhkmfCDSKstZKyrHmJwFIk8WYe8DDbbH
meAybaDJfGfieQ46lhwP/tgq8VEM7m/bhkhksXHTuKmPGfr53uev9Rp1+TKG1vFW
2c8MFMrDg3ZNy8lAfZmhIWUP9ietU5o836d0/3vJ+nBeSZwhAkEA+0luT5ijhfh4
Jim81h0yKJFOeg/gjdHtefAWyruAGHZEKz+yLNTPJN0bjPtQAOqSr/Hjt9MmxzPa
HJ0DuvvgbQJBAPEF1mYmqmpBZTDc2zjOTXzVRsNO/bBcx/q9GkQydn/7BV6Dqr9Y
cgJV49CWcbZBHLkCxyidKDvZBzTh0b/vWTkCQH3AsLianXLk9lO63WqVb82Hcit5
mJnAbcRxFybbkG4teU3fcW4oDYXYNPpnphDfUwtD1P7gZ26XD1b0aLKBbD0CQQC3
sCY9Rfyc7GgNfFTLD1e46uZ6VUo8zglPDC3niboMQahO5vQLzoFdTE5Km03gg/E7
A2X7iwKt0fKPGAd+SxDpAkEA6OG77IL8cjrlZKk4ilTCz8rkF4CtZWbDLi1IF40i
jaGlSLvVowHDywtjT8tYfpIH7HI55KS3gj88qAaF38qfRA==
-----END RSA PRIVATE KEY-----

6
cert/pub_key.pem

@ -0,0 +1,6 @@
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDsldu7vayXD7RE5HEMsvlz/tkq
36gBgY1Yz+R9dkZWNDdQTTFmO2tWFwBvYRx5Nv/CtR1Nl2+pb/Nd6WrWzs9FR7P8
4nixA+vfzQjqTIlQViO0vB/agWa2nk5N4e0dsQ7kDr3+7/w1DeFsMlRBDvSHMsdm
lNSFDFB6+MVrC93dRQIDAQAB
-----END PUBLIC KEY-----

4
composer.json

@ -11,8 +11,8 @@
], ],
"minimum-stability": "dev", "minimum-stability": "dev",
"require": { "require": {
"yiisoft/yii2": "^2.0@dev",
"swoole/ide-helper": "dev-master"
"swoole/ide-helper": "dev-master",
"firebase/php-jwt": "dev-master"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {

414
composer.lock

@ -4,86 +4,20 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "04cbcc938ac71579c75a6ca70e0a613c",
"content-hash": "be484b9b2956b9cbaf4eac46f8dd344a",
"packages": [ "packages": [
{ {
"name": "cebe/markdown",
"version": "1.1.2",
"source": {
"type": "git",
"url": "https://github.com/cebe/markdown.git",
"reference": "25b28bae8a6f185b5030673af77b32e1163d5c6e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/cebe/markdown/zipball/25b28bae8a6f185b5030673af77b32e1163d5c6e",
"reference": "25b28bae8a6f185b5030673af77b32e1163d5c6e",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"lib-pcre": "*",
"php": ">=5.4.0"
},
"require-dev": {
"cebe/indent": "*",
"facebook/xhprof": "*@dev",
"phpunit/phpunit": "4.1.*"
},
"bin": [
"bin/markdown"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1.x-dev"
}
},
"autoload": {
"psr-4": {
"cebe\\markdown\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Carsten Brandt",
"email": "mail@cebe.cc",
"homepage": "http://cebe.cc/",
"role": "Creator"
}
],
"description": "A super fast, highly extensible markdown parser for PHP",
"homepage": "https://github.com/cebe/markdown#readme",
"keywords": [
"extensible",
"fast",
"gfm",
"markdown",
"markdown-extra"
],
"time": "2017-07-16T21:13:23+00:00"
},
{
"name": "psr/http-message",
"name": "firebase/php-jwt",
"version": "dev-master", "version": "dev-master",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/php-fig/http-message.git",
"reference": "efd67d1dc14a7ef4fc4e518e7dee91c271d524e4"
"url": "https://github.com/firebase/php-jwt.git",
"reference": "feb0e820b8436873675fd3aca04f3728eb2185cb"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/php-fig/http-message/zipball/efd67d1dc14a7ef4fc4e518e7dee91c271d524e4",
"reference": "efd67d1dc14a7ef4fc4e518e7dee91c271d524e4",
"url": "https://api.github.com/repos/firebase/php-jwt/zipball/feb0e820b8436873675fd3aca04f3728eb2185cb",
"reference": "feb0e820b8436873675fd3aca04f3728eb2185cb",
"shasum": "", "shasum": "",
"mirrors": [ "mirrors": [
{ {
@ -95,145 +29,38 @@
"require": { "require": {
"php": ">=5.3.0" "php": ">=5.3.0"
}, },
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for HTTP messages",
"homepage": "https://github.com/php-fig/http-message",
"keywords": [
"http",
"http-message",
"psr",
"psr-7",
"request",
"response"
],
"time": "2019-08-29T13:16:46+00:00"
},
{
"name": "psr/log",
"version": "1.0.2",
"source": {
"type": "git",
"url": "https://github.com/php-fig/log.git",
"reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/log/zipball/4ebe3a8bf773a19edfe0a84b6585ba3d401b724d",
"reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"php": ">=5.3.0"
"require-dev": {
"phpunit/phpunit": ">=4.8 <=9"
}, },
"type": "library", "type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"Psr\\Log\\": "Psr/Log/"
"Firebase\\JWT\\": "src"
} }
}, },
"notification-url": "https://packagist.org/downloads/", "notification-url": "https://packagist.org/downloads/",
"license": [ "license": [
"MIT"
"BSD-3-Clause"
], ],
"authors": [ "authors": [
{ {
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for logging libraries",
"homepage": "https://github.com/php-fig/log",
"keywords": [
"log",
"psr",
"psr-3"
],
"time": "2016-10-10T12:19:37+00:00"
},
{
"name": "psr/simple-cache",
"version": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/php-fig/simple-cache.git",
"reference": "5a7b96b1dda5d957e01bc1bfe77dcca09c5a7474"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/simple-cache/zipball/5a7b96b1dda5d957e01bc1bfe77dcca09c5a7474",
"reference": "5a7b96b1dda5d957e01bc1bfe77dcca09c5a7474",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\SimpleCache\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
"name": "Neuman Vong",
"email": "neuman+pear@twilio.com",
"role": "Developer"
},
{ {
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
"name": "Anant Narayanan",
"email": "anant@php.net",
"role": "Developer"
} }
], ],
"description": "Common interfaces for simple caching",
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
"homepage": "https://github.com/firebase/php-jwt",
"keywords": [ "keywords": [
"cache",
"caching",
"psr",
"psr-16",
"simple-cache"
"jwt",
"php"
], ],
"time": "2020-04-21T06:43:17+00:00"
"time": "2020-03-25T18:49:23+00:00"
}, },
{ {
"name": "swoole/ide-helper", "name": "swoole/ide-helper",
@ -241,12 +68,12 @@
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/swoole/ide-helper.git", "url": "https://github.com/swoole/ide-helper.git",
"reference": "e45892fb913204fc776bdec019ca8b723e7249b1"
"reference": "9082983c671cd79f461fcb9e52687dccca993e9b"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/swoole/ide-helper/zipball/e45892fb913204fc776bdec019ca8b723e7249b1",
"reference": "e45892fb913204fc776bdec019ca8b723e7249b1",
"url": "https://api.github.com/repos/swoole/ide-helper/zipball/9082983c671cd79f461fcb9e52687dccca993e9b",
"reference": "9082983c671cd79f461fcb9e52687dccca993e9b",
"shasum": "", "shasum": "",
"mirrors": [ "mirrors": [
{ {
@ -273,200 +100,15 @@
} }
], ],
"description": "IDE help files for Swoole.", "description": "IDE help files for Swoole.",
"time": "2020-05-28T19:17:49+00:00"
},
{
"name": "yiisoft/yii2",
"version": "2.1.x-dev",
"source": {
"type": "git",
"url": "https://github.com/yiisoft/yii2-framework.git",
"reference": "86f1bfd7016524a6988005f3cdf9d01528df39fb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/yiisoft/yii2-framework/zipball/86f1bfd7016524a6988005f3cdf9d01528df39fb",
"reference": "86f1bfd7016524a6988005f3cdf9d01528df39fb",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"cebe/markdown": "~1.0.0 | ~1.1.0",
"ext-ctype": "*",
"ext-mbstring": "*",
"lib-pcre": "*",
"php": ">=7.1.0",
"psr/http-message": "~1.0.0",
"psr/log": "~1.0.2",
"psr/simple-cache": "~1.0.0",
"yiisoft/yii2-composer": "~2.0.4"
},
"suggest": {
"ezyang/htmlpurifier": "version '~4.6' required at 'yii\\helpers\\HtmlPurifier' for 'html' data format support (e.g. 'yii\\i18n\\Formatter:asHtml()' and 'yii\\helpers\\StringHelper::truncateHtml()')"
},
"bin": [
"yii"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0.x-dev"
}
},
"autoload": {
"psr-4": {
"yii\\": ""
},
"classmap": [
"Yii.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Qiang Xue",
"email": "qiang.xue@gmail.com",
"homepage": "http://www.yiiframework.com/",
"role": "Founder and project lead"
},
{
"name": "Alexander Makarov",
"email": "sam@rmcreative.ru",
"homepage": "http://rmcreative.ru/",
"role": "Core framework development"
},
{
"name": "Maurizio Domba",
"homepage": "http://mdomba.info/",
"role": "Core framework development"
},
{
"name": "Carsten Brandt",
"email": "mail@cebe.cc",
"homepage": "http://cebe.cc/",
"role": "Core framework development"
},
{
"name": "Timur Ruziev",
"email": "resurtm@gmail.com",
"homepage": "http://resurtm.com/",
"role": "Core framework development"
},
{
"name": "Paul Klimov",
"email": "klimov.paul@gmail.com",
"role": "Core framework development"
},
{
"name": "Dmitry Naumenko",
"email": "d.naumenko.a@gmail.com",
"role": "Core framework development"
},
{
"name": "Boudewijn Vahrmeijer",
"email": "info@dynasource.eu",
"homepage": "http://dynasource.eu",
"role": "Core framework development"
}
],
"description": "Yii PHP Framework Version 2",
"homepage": "http://www.yiiframework.com/",
"keywords": [
"framework",
"yii2"
],
"time": "2018-06-12T19:38:40+00:00"
},
{
"name": "yiisoft/yii2-composer",
"version": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/yiisoft/yii2-composer.git",
"reference": "c372400aa6b6f2c52a82764496b37eb50d6e479f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/yiisoft/yii2-composer/zipball/c372400aa6b6f2c52a82764496b37eb50d6e479f",
"reference": "c372400aa6b6f2c52a82764496b37eb50d6e479f",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"composer-plugin-api": "^1.0 | ^2.0"
},
"require-dev": {
"composer/composer": "^1.0 | ^2.0@dev",
"phpunit/phpunit": "<7"
},
"type": "composer-plugin",
"extra": {
"class": "yii\\composer\\Plugin",
"branch-alias": {
"dev-master": "2.0.x-dev"
}
},
"autoload": {
"psr-4": {
"yii\\composer\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Qiang Xue",
"email": "qiang.xue@gmail.com"
},
{
"name": "Carsten Brandt",
"email": "mail@cebe.cc"
}
],
"description": "The composer plugin for Yii extension installer",
"keywords": [
"composer",
"extension installer",
"yii2"
],
"funding": [
{
"url": "https://github.com/yiisoft",
"type": "github"
},
{
"url": "https://opencollective.com/yiisoft",
"type": "open_collective"
},
{
"url": "https://tidelift.com/funding/github/packagist/yiisoft/yii2-composer",
"type": "tidelift"
}
],
"time": "2020-06-24T00:04:19+00:00"
"time": "2020-08-05T18:18:55+00:00"
} }
], ],
"packages-dev": [], "packages-dev": [],
"aliases": [], "aliases": [],
"minimum-stability": "dev", "minimum-stability": "dev",
"stability-flags": { "stability-flags": {
"yiisoft/yii2": 20,
"swoole/ide-helper": 20
"swoole/ide-helper": 20,
"firebase/php-jwt": 20
}, },
"prefer-stable": false, "prefer-stable": false,
"prefer-lowest": false, "prefer-lowest": false,

33
examples/client.php

@ -4,10 +4,10 @@
* struct * struct
* { * {
* unisgned char type; * unisgned char type;
* uint32_t time;
* uint32_t serid;
* uint32_t length;
* char body[0];
* unsigned int time;
* unsigned int serid;
* unsigned int length;
* char body[length];
* } * }
*/ */
function remoteCall(string $host, $port, string $data) { function remoteCall(string $host, $port, string $data) {
@ -28,15 +28,30 @@ function remoteCall(string $host, $port, string $data) {
} }
$client->send($pack); $client->send($pack);
$pack = $client->recv();
$pack = @$client->recv();
$client->close();
if ($pack === false) {
//echo $client->errCode . "\n";
//TODO 获取错误码并进行处理
return false;
} else if (empty($pack)) {
echo "close by peer\n";
return false;
}
$ret = unpack('Ctype/Ntime/Nserid/Nlength/a*data', $pack); $ret = unpack('Ctype/Ntime/Nserid/Nlength/a*data', $pack);
return $ret['data']; return $ret['data'];
} }
$ret = remoteCall("127.0.0.1", "5188", "sasa");
echo $ret;
$c = 0;
while(1){
$c++;
$ret = remoteCall("127.0.0.1", "5188", '{"controller":"site","methor":"test","params":{"id":'.$c.',"status":0}}');
echo "{$ret}\n";
break;
}
//var_dump($ret);
?> ?>

2
examples/index.php

@ -5,4 +5,4 @@ include __DIR__ . "/../vendor/autoload.php";
use blobt\airpc\Yee; use blobt\airpc\Yee;
return (new Yee())->run();
return Yee::getInstaance()->run();

206
examples/rsa_test.php

@ -0,0 +1,206 @@
<?php
include __DIR__ . "/../vendor/autoload.php";
use \Firebase\JWT\JWT;
$key = "73937393";
$privateKey = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDsldu7vayXD7RE5HEMsvlz/tkq36gBgY1Yz+R9dkZWNDdQTTFm
O2tWFwBvYRx5Nv/CtR1Nl2+pb/Nd6WrWzs9FR7P84nixA+vfzQjqTIlQViO0vB/a
gWa2nk5N4e0dsQ7kDr3+7/w1DeFsMlRBDvSHMsdmlNSFDFB6+MVrC93dRQIDAQAB
AoGBALhxeJZcIDLA7oSLKEuDOJEjDQGszhkmfCDSKstZKyrHmJwFIk8WYe8DDbbH
meAybaDJfGfieQ46lhwP/tgq8VEM7m/bhkhksXHTuKmPGfr53uev9Rp1+TKG1vFW
2c8MFMrDg3ZNy8lAfZmhIWUP9ietU5o836d0/3vJ+nBeSZwhAkEA+0luT5ijhfh4
Jim81h0yKJFOeg/gjdHtefAWyruAGHZEKz+yLNTPJN0bjPtQAOqSr/Hjt9MmxzPa
HJ0DuvvgbQJBAPEF1mYmqmpBZTDc2zjOTXzVRsNO/bBcx/q9GkQydn/7BV6Dqr9Y
cgJV49CWcbZBHLkCxyidKDvZBzTh0b/vWTkCQH3AsLianXLk9lO63WqVb82Hcit5
mJnAbcRxFybbkG4teU3fcW4oDYXYNPpnphDfUwtD1P7gZ26XD1b0aLKBbD0CQQC3
sCY9Rfyc7GgNfFTLD1e46uZ6VUo8zglPDC3niboMQahO5vQLzoFdTE5Km03gg/E7
A2X7iwKt0fKPGAd+SxDpAkEA6OG77IL8cjrlZKk4ilTCz8rkF4CtZWbDLi1IF40i
jaGlSLvVowHDywtjT8tYfpIH7HI55KS3gj88qAaF38qfRA==
-----END RSA PRIVATE KEY-----
EOD;
$publicKey = <<<EOD
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDsldu7vayXD7RE5HEMsvlz/tkq
36gBgY1Yz+R9dkZWNDdQTTFmO2tWFwBvYRx5Nv/CtR1Nl2+pb/Nd6WrWzs9FR7P8
4nixA+vfzQjqTIlQViO0vB/agWa2nk5N4e0dsQ7kDr3+7/w1DeFsMlRBDvSHMsdm
lNSFDFB6+MVrC93dRQIDAQAB
-----END PUBLIC KEY-----
EOD;
$payload = [
'id' => 'backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'components' => [
'assetManager' => [
'baseUrl' => '@web' . (getenv('KUBERNETES_NAMESPACE') ? '/' . getenv('KUBERNETES_NAMESPACE') : '') . '/assets'
],
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
'csrfParam' => '_csrf-api',
],
'user' => [
'identityClass' => 'backend\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the app
'name' => 'backend',
],
'log' => [
'traceLevel' => 1,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['info', 'error'],
'categories' => ['imagetest'],
'logFile' => '@app/runtime/logs/imagetest.log',
'logVars' => [],
'exportInterval' => 1,
'prefix' => function ($message) {
}
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning', 'info'],
'categories' => ['refund_log'],
'logFile' => '@app/runtime/logs/refund_log.log',
'logVars' => [],
'exportInterval' => 1,
'prefix' => function ($message) {
}
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning', 'info'],
'categories' => ['obj'],
'logFile' => '@app/runtime/logs/obj.log',
'logVars' => [],
'exportInterval' => 1,
'prefix' => function ($message) {
}
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' =>
getenv('KUBERNETES_NAMESPACE') ? [
getenv('KUBERNETES_NAMESPACE') . '/<rule:[\S-]+>' => '<rule>'
] : [],
],
'goods' => ['class' => 'goods\goods\logic\goods\GoodsManager'],
],
'as access' => [
'class' => 'iron\components\AccessControl',
'allowActions' => [
'site/catch-permission',
]
],
'params' => [
'assetManager' => [
'baseUrl' => '@web' . (getenv('KUBERNETES_NAMESPACE') ? '/' . getenv('KUBERNETES_NAMESPACE') : '') . '/assets'
],
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
'csrfParam' => '_csrf-api',
],
'user' => [
'identityClass' => 'backend\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the app
'name' => 'backend',
],
'log' => [
'traceLevel' => 1,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['info', 'error'],
'categories' => ['imagetest'],
'logFile' => '@app/runtime/logs/imagetest.log',
'logVars' => [],
'exportInterval' => 1,
'prefix' => function ($message) {
}
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning', 'info'],
'categories' => ['refund_log'],
'logFile' => '@app/runtime/logs/refund_log.log',
'logVars' => [],
'exportInterval' => 1,
'prefix' => function ($message) {
}
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning', 'info'],
'categories' => ['obj'],
'logFile' => '@app/runtime/logs/obj.log',
'logVars' => [],
'exportInterval' => 1,
'prefix' => function ($message) {
}
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' =>
getenv('KUBERNETES_NAMESPACE') ? [
getenv('KUBERNETES_NAMESPACE') . '/<rule:[\S-]+>' => '<rule>'
] : [],
],
'goods' => ['class' => 'goods\goods\logic\goods\GoodsManager'],
],
];
$jwt = JWT::encode($payload, $privateKey, 'RS256');
echo strlen($jwt) . "\n";
echo "Encode:\n" . print_r($jwt, true) . "\n";
$decoded = JWT::decode($jwt, $publicKey, array('RS256'));
$decoded_array = (array) $decoded;
echo "Decode:\n" . print_r($decoded_array, true) . "\n";

4
examples/server.php

@ -13,5 +13,9 @@ include __DIR__."/../vendor/autoload.php";
use blobt\airpc\RpcServer; use blobt\airpc\RpcServer;
$server = new RpcServer("0.0.0.0", 5188); $server = new RpcServer("0.0.0.0", 5188);
$server->reactorNum = 2;
$server->workerNum = 6;
$server->daemonize = false;
$server->entryPoint = '/home/blobt/Documents/dev/php/yii2-app-rpc/rpc/index.php';
$server->run(); $server->run();
?> ?>

63
examples/test.php

@ -1,17 +1,50 @@
<?php <?php
$units = array();
for($i=0;$i<1000000;$i++){
$units[] = uniqid();
echo $units[$i].PHP_EOL;
}
$values = array_count_values($units);
$duplicates = [];
foreach($values as $k=>$v){
if($v>1){
$duplicates[$k]=$v;
}
}
echo '<pre>';
print_r($duplicates);
echo '</pre>';
include __DIR__ . "/../vendor/autoload.php";
use \Firebase\JWT\JWT;
$privateKey = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDsldu7vayXD7RE5HEMsvlz/tkq36gBgY1Yz+R9dkZWNDdQTTFm
O2tWFwBvYRx5Nv/CtR1Nl2+pb/Nd6WrWzs9FR7P84nixA+vfzQjqTIlQViO0vB/a
gWa2nk5N4e0dsQ7kDr3+7/w1DeFsMlRBDvSHMsdmlNSFDFB6+MVrC93dRQIDAQAB
AoGBALhxeJZcIDLA7oSLKEuDOJEjDQGszhkmfCDSKstZKyrHmJwFIk8WYe8DDbbH
meAybaDJfGfieQ46lhwP/tgq8VEM7m/bhkhksXHTuKmPGfr53uev9Rp1+TKG1vFW
2c8MFMrDg3ZNy8lAfZmhIWUP9ietU5o836d0/3vJ+nBeSZwhAkEA+0luT5ijhfh4
Jim81h0yKJFOeg/gjdHtefAWyruAGHZEKz+yLNTPJN0bjPtQAOqSr/Hjt9MmxzPa
HJ0DuvvgbQJBAPEF1mYmqmpBZTDc2zjOTXzVRsNO/bBcx/q9GkQydn/7BV6Dqr9Y
cgJV49CWcbZBHLkCxyidKDvZBzTh0b/vWTkCQH3AsLianXLk9lO63WqVb82Hcit5
mJnAbcRxFybbkG4teU3fcW4oDYXYNPpnphDfUwtD1P7gZ26XD1b0aLKBbD0CQQC3
sCY9Rfyc7GgNfFTLD1e46uZ6VUo8zglPDC3niboMQahO5vQLzoFdTE5Km03gg/E7
A2X7iwKt0fKPGAd+SxDpAkEA6OG77IL8cjrlZKk4ilTCz8rkF4CtZWbDLi1IF40i
jaGlSLvVowHDywtjT8tYfpIH7HI55KS3gj88qAaF38qfRA==
-----END RSA PRIVATE KEY-----
EOD;
$publicKey = <<<EOD
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDsldu7vayXD7RE5HEMsvlz/tkq
36gBgY1Yz+R9dkZWNDdQTTFmO2tWFwBvYRx5Nv/CtR1Nl2+pb/Nd6WrWzs9FR7P8
4nixA+vfzQjqTIlQViO0vB/agWa2nk5N4e0dsQ7kDr3+7/w1DeFsMlRBDvSHMsdm
lNSFDFB6+MVrC93dRQIDAQAB
-----END PUBLIC KEY-----
EOD;
$data = [
'id' => 23,
'name' => 'nemo'
];
//$encode = JWT::encode($data, $privateKey, 'RS256');
$encode = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eeyJpZCI6MjMsIm5hbWUiOiJuZW1vIn0.xJt8NHFJeQyiWSmAI1C_t2lX99QHChXpR7iNkTQ5oi7_87NPo_S4gbC2zh40SOmv9uk3EoRvsrzzRbtPSeh7D5oCbSVXcqvVwMq0zwYBgW6vyL5DMkuDGyQQpyVGuywy8xY9N9bwUtiL7tVj_S22L1jaYOw7SZtGU4eDa5vU_DM";
echo "encode: " . $encode . "\n";
$decoded = (array) JWT::decode($encode, $publicKey, array('RS256'));
print_r($decoded);
?> ?>

242
src/BaseService.php

@ -0,0 +1,242 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace blobt\airpc;
use Swoole;
/**
* Description of Service
*
* @author blobt
*/
abstract class BaseService {
/**
* @var Swoole\Http\Server
*/
public $server = null;
/**
* @var integral worker进程数量,worker进程是用来处理链接的,默认是cpu核心数
*/
public $workerNum = 4;
/**
* @var integral reactor线程数量,reactor线程是用来分发fd到worker的,默认是cpu核心数
*/
public $reactorNum = 1;
/**
* @var integral task进程数目
*/
public $taskWorkerNum = 0;
/**
* @var integral 最大处理任务数量,处理玩最大任务数量个任务后,进程会自动烧毁,用来防止内存泄漏
*/
public $maxRequest = 0;
/**
* @var integral 最大链接数
*/
public $maxConn = 1000;
/**
* @var bool是否以守护进程模式运行
*/
public $daemonize = false;
/**
* @var Swoole\Table
*/
public $table = null;
/**
* @var integral 发送序列号
*/
private $serid = 0;
/**
* @var integral 接收序列号
*/
private $revid = 0;
/**
* @var string 全局数据
*/
public $data;
/**
* @var array swoole配置数组
*/
public $config;
/**
* @param string $listen 监听地址
* @param integral $port 监听端口
*/
public function __construct($listen, $port) {
$this->server = new \Swoole\Server($listen, $port, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
$this->config = [
'worker_num' => $this->workerNum,
'reactor_num' => $this->reactorNum,
'task_worker_num' => $this->taskWorkerNum,
'max_request' => $this->maxRequest,
'max_conn' => $this->maxConn,
'daemonize' => $this->daemonize
];
}
/**
* 初始化
*/
public function init() {
}
/**
* 注册swoole事件
* 所有以on开头函数都会被认为是swoole事件函数,函数名为事件名,并自动注册
*/
private function setEvents() {
$methods = get_class_methods(self::class);
foreach ($methods as $method) {
if (strncmp($method, "on", 2) === 0) {
$event = substr($method, 2);
$this->server->on($event, [$this, $method]);
}
}
}
/**
* 配置swoole参数
*/
private function setConfig() {
$this->server->set($this->config);
}
/**
* 设置协议
* @param char $type 储存包体长度的字节,N代表大端字节序的4个字节
* @param integral $maxLength 数据包最大长度
* @param integral $lengthOffset 从包体的第几个字节开始是包体长度信息
* @param integral $bodyOffset 从包体的第几个字节开始是包体信息
*/
public function setProtocol($type, $maxLength, $lengthOffset, $bodyOffset) {
$this->config['open_length_check'] = true;
$this->config['package_length_type'] = $type;
$this->config['package_max_length'] = $maxLength;
$this->config['package_length_offset'] = $lengthOffset;
$this->config['package_body_offset'] = $bodyOffset;
}
/**
* master 进程启动时候执行函数
* @param Swoole\Server $server
*/
public function onStart(Swoole\Server $server) {
swoole_set_process_name("ai:master");
}
/**
* manager进程启动时候执行函数
* @param Swoole\Server $server
*/
public function onManagerStart(Swoole\Server $server) {
swoole_set_process_name("ai:manager");
}
/**
* worker进程启动后执行的回调
* @param Swoole\Server $server
* @param int $workerId
*/
public function onWorkerStart(Swoole\Server $server, int $workerId) {
swoole_set_process_name("ai:worker{$workerId}");
}
/**
*
* @param Swoole\Server $server
* @param int $fd
* @param int $reactorId
* @param string $pack
*/
abstract public function onReceive(Swoole\Server $server, int $fd, int $reactorId, string $pack);
/**
* task 处理函数
* @param Swoole\Server $server
* @param int $task_id
* @param int $src_worker_id
* @param mixed $data
*/
public function onTask(Swoole\Server $server, int $task_id, int $src_worker_id, $data) {
//TODO
}
/**
* 链接成功事件处理
* @param Swoole\Server $server
* @param int $fd
* @param int $reactorId
*/
public function onConnect(Swoole\Server $server, int $fd, int $reactorId) {
//TODO
}
/**
* 错误处理
* @param Swoole\Server $server
* @param int $worker_id
* @param int $worker_pid
* @param int $exit_code
* @param int $signal
*/
function onWorkerError(Swoole\Server $server, int $worker_id, int $worker_pid, int $exit_code, int $signal) {
//TODO
}
/**
* worker进程停止
* @param Swoole\Server $server
* @param int $workerId
*/
function onWorkerStop(Swoole\Server $server, int $workerId) {
//TODO
}
/**
* 关闭链接时候触发
* @param Swoole\Server $server
* @param int $fd
* @param int $reactorId
*/
public function onClose(Swoole\Server $server, int $fd, int $reactorId) {
//TODO
}
/**
* 启动swoole
*/
public function start() {
$this->server->start();
}
/**
* 服务启动
*/
public function run() {
$this->init();
$this->setConfig();
$this->setEvents();
$this->start();
}
}

160
src/Pack.php

@ -0,0 +1,160 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace blobt\airpc;
/**
*
* @author blobt
* Rpc协议 0.3
* struct
* {
* unisgned char type;
* unsigned int time;
* unisgned int serid;
* unsigned int length;
* char body[0];
* }
*/
class Pack {
/**
* 发送的数据类型
*/
const DATA_TYPE_SAMPLE_DATA = 1;
/**
* @var integral 包的最大长度
*/
static public $packageMaxLength = 1024 * 20;
/**
* @var char 储存包体长度的字节数,N代表大端字节序的4个字节
*/
static public $packageLengthType = 'N';
/**
* @var integral 从包体的第几个字节开始是包体长度信息
*/
static public $packageLengthOffset = 9;
/**
* @var 从包体的第几个字节开始是包体信息
*/
static public $packageBodyOffset = 13;
/**
* @var 该数组定义了协议包每一项的字节大小和名称
*/
private $items = [
'type' => 'C',
'time' => 'N',
'serid' => 'N',
'length' => 'N',
'data' => 'a*'
];
/**
* @var integral 包的类型
*/
public $type;
/**
* @var string 包体数据
*/
public $data;
/**
* @var integral 包生成的时间
*/
public $time;
/**
* @var integral 包的序列id
*/
public $serid = 0;
/**
* @var integral 包体长度
*/
public $length;
/**
* 创建包分两种情况,$data可以是二进制流,也可以是字符数据
* @param string $data 包体数据
* @param type $serid 包的序列号
*/
public function __construct(string $data, $serid = 0) {
$ret = $this->unpack($data);
if (is_array($ret)) {
$this->type = $ret['type'];
$this->time = $ret['time'];
$this->serid = $ret['serid'];
$this->length = $ret['length'];
$this->data = $ret['data'];
} else {
$this->type = self::DATA_TYPE_SAMPLE_DATA;
$this->data = $data;
$this->serid = $serid;
$this->length = strlen($data);
$this->data = $data;
}
}
/**
* 生产格式字符串
* @param boolean $isUnpack
*/
private function makeFormat($isUnpack = false) {
$format = '';
if ($isUnpack) {
foreach ($this->items as $k => $v) {
$format .= "{$v}{$k}/";
}
$format = substr($format, 0, -1);
} else {
foreach ($this->items as $k => $v) {
$format .= $v;
}
}
return $format;
}
/**
* 数据打包,数据打包成二进制流
* @return string
*/
public function pack() {
return pack($this->makeFormat(), $this->type, $this->time, $this->serid, $this->length, $this->data);
}
/**
* 解包,把二进制流转换成格式数组
* @param string $pack
* @return string | boolean
*/
public function unpack(string $pack) {
$ret = unpack($this->makeFormat(true), $pack);
if ($ret['type'] == self::DATA_TYPE_SAMPLE_DATA
&& $ret['length'] == strlen($ret['data'])
&& (int) $ret['length'] <= self::$packageMaxLength) {
return $ret;
}
return false;
}
/**
*
* @return string
*/
public function __toString() {
return $this->pack();
}
}

25
src/Protocol.php

@ -1,25 +0,0 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace blobt\airpc;
/**
* struct
* {
* unisgned char type;
* uint32_t time;
* uint32_t serid;
* uint32_t length;
* char body[0];
* }
*
* @author blobt
*/
class Protocol {
//put your code here
}

257
src/RpcServer.php

@ -3,270 +3,71 @@
namespace blobt\airpc; namespace blobt\airpc;
use Swoole; use Swoole;
use Swoole\Table as Table;
use blobt\airpc\Pack;
/** /**
* 基于swoole的轻量及 RPC * 基于swoole的轻量及 RPC
* 服务器 * 服务器
* *
* Rpc协议 0.3
* struct
* {
* unisgned char type;
* unsigned int time;
* unisgned int serid;
* unsigned int length;
* char body[0];
* }
*/ */
class RpcServer {
class RpcServer extends BaseService {
/** /**
* 发送的数据类型
* @var string rpc项目入口文件
*/ */
const DATA_TYPE_SAMPLE_DATA = 1;
/**
* @var Swoole\Http\Server
*/
public $server = null;
/**
* @var integral worker进程数量,worker进程是用来处理链接的,默认是cpu核心数
*/
public $workerNum = 4;
/**
* @var integral reactor线程数量,reactor线程是用来分发fd到worker的,默认是cpu核心数
*/
public $reactorNum = 1;
/**
* @var integral task进程数目
*/
public $taskWorkerNum = 0;
/**
* @var integral 最大处理任务数量,处理玩最大任务数量个任务后,进程会自动烧毁,用来防止内存泄漏
*/
public $maxRequest = 0;
/**
* @var integral 最大链接数
*/
public $maxConn = 1000;
/**
* @var bool是否以守护进程模式运行
*/
public $daemonize = false;
/**
* @var Swoole\Table
*/
public $table = null;
/**
* @var 数据包的最大长度
*/
public $packageMaxLength = 1024 * 20;
/**
* @var integral 发送序列号
*/
private $serid = 0;
/**
* @var integral 接收序列号
*/
private $revid = 0;
/**
* 服务初始化
* @param string $listen 监听地址
* @param integral $port 监听端口
*/
public function __construct($listen, $port) {
$this->server = new \Swoole\Server($listen, $port, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
$this->init();
}
/**
* 配置swoole参数
*/
private function setting() {
$config = [
'worker_num' => $this->workerNum,
'reactor_num' => $this->reactorNum,
'task_worker_num' => $this->taskWorkerNum,
'max_request' => $this->maxRequest,
'max_conn' => $this->maxConn,
'daemonize' => $this->daemonize,
'open_length_check' => true,
'package_max_length' => $packageMaxLength,
'package_length_type' => 'N',
'package_length_offset' => 9,
'package_body_offset' => 13
];
$this->server->set($config);
}
public $entryPoint = false;
/** /**
* 初始化 * 初始化
*/ */
public function init() { public function init() {
$this->setting();
$this->server->on('Close', [$this, "close"]);
$this->server->on("Start", [$this, "start"]);
$this->server->on("ManagerStart", [$this, "managerStart"]);
$this->server->on("WorkerStart", [$this, "workerStart"]);
$this->server->on("Task", [$this, "task"]);
$this->server->on("Connect", [$this, "connect"]);
$this->server->on("Receive", [$this, "receive"]);
$this->server->on("WorkerError", [$this, "error"]);
$this->server->on("WorkerStop", [$this, "stop"]);
}
/**
* master 进程启动时候执行函数
* @param Swoole\Server $server
*/
public function start(Swoole\Server $server) {
swoole_set_process_name("php:master");
}
/**
* manager进程启动时候执行函数
* @param Swoole\Server $server
*/
public function managerStart(Swoole\Server $server) {
swoole_set_process_name("php:manager");
}
/**
* worker进程启动后执行的回调
* @param Swoole\Server $server
* @param int $workerId
*/
public function workerStart(Swoole\Server $server, int $workerId) {
swoole_set_process_name("php:worker{$workerId}");
if (empty($this->entryPoint)) {
die("Please set the entry point." . PHP_EOL);
}
$this->setProtocol(Pack::$packageLengthType, Pack::$packageMaxLength, Pack::$packageLengthOffset, Pack::$packageBodyOffset);
} }
/** /**
* task 处理函数
* @param Swoole\Server $server
* @param int $task_id
* @param int $src_worker_id
* @param mixed $data
* 发送数据
* @param integral $fd 链接文件描述付
* @param string $data
* @return boolean
*/ */
public function task(Swoole\Server $server, int $task_id, int $src_worker_id, $data) {
echo "task: {$data}\n";
public function send(int $fd, string $data) {
$pack = new Pack($data);
$this->server->send($fd, (string) $pack);
} }
/** /**
* 链接成功事件处理
*
* @param Swoole\Server $server * @param Swoole\Server $server
* @param int $fd * @param int $fd
* @param int $reactorId * @param int $reactorId
* @param string $pack
*/ */
public function connect(Swoole\Server $server, int $fd, int $reactorId) {
//echo "connected: {$fd} {$reactorId}\n";
public function onReceive(Swoole\Server $server, int $fd, int $reactorId, string $pack) {
$pack = new Pack($pack);
$data = $pack->data;
$this->handle($fd, $data);
} }
/** /**
*
* @param Swoole\Server $server
* 请求处理函数
* @param int $fd * @param int $fd
* @param int $reactorId
* @param string $pack * @param string $pack
*/ */
public function receive(Swoole\Server $server, int $fd, int $reactorId, string $pack) {
//解包返回请求数据
$data = $this->unpack($pack);
public function handle(int $fd, string $data) {
$_SERVER['data'] = $data;
try { try {
$ret = include __DIR__ . '/../examples/index.php';
$ret = include $this->entryPoint;
$this->send($fd, $ret); $this->send($fd, $ret);
} catch (\Error $e) { } catch (\Error $e) {
$this->send($fd, "YeeError:" . $e->getMessage());
print_r($e);
$this->send($fd, "YeeError");
} catch (\Exception $e) { } catch (\Exception $e) {
$this->send($fd, "YeeException:" . $e->getMessage());
}
}
/**
* 关闭链接时候触发
* @param Swoole\Server $server
* @param int $fd
* @param int $reactorId
*/
public function close(Swoole\Server $server, int $fd, int $reactorId) {
//echo "connection close: {$fd} {$reactorId}\n";
}
/**
* 错误处理
* @param Swoole\Server $server
* @param int $worker_id
* @param int $worker_pid
* @param int $exit_code
* @param int $signal
*/
function error(Swoole\Server $server, int $worker_id, int $worker_pid, int $exit_code, int $signal) {
//echo "\nError\n";
}
/**
* worker进程停止
* @param Swoole\Server $server
* @param int $workerId
*/
function Stop(Swoole\Server $server, int $workerId) {
//echo "\nStop\n";
}
/**
* 数据打包,添加包头和包体
* @param string $data
* @return string
*/
public function pack(string $data) {
$length = strlen($data);
$pack = pack('CNNNa*', self::DATA_TYPE_SAMPLE_DATA, time(), ++$this->serid, $length, $data);
return $pack;
}
/**
* 解包,获取报文数据
* @param string $pack
* @return string
*/
public function unpack(string $pack) {
$ret = unpack('Ctype/Ntime/Nserid/Nlength/a*data', $pack);
if (isset($ret['data'])) {
//TODO 记录日志, 次包不完整
print_r($e);
$this->send($fd, "YeeException");
} }
return $ret['data'];
}
/**
* 发送数据
* @param integral $fd 链接文件描述付
* @param string $data
* @return boolean
*/
public function send(int $fd, string $data) {
$pack = $this->pack($data);
$this->server->send($fd, $pack);
}
/**
* 服务启动
*/
public function run() {
$this->server->start();
} }
} }

14
src/Yee.php

@ -3,11 +3,21 @@
namespace blobt\airpc; namespace blobt\airpc;
use yii\console\controllers\HelpController; use yii\console\controllers\HelpController;
class Yee { class Yee {
private static $instance;
public static function getInstaance() {
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function run() { public function run() {
return "some datasasa";
$ret = "some data ".$_SERVER['data'];
return $ret;
} }
} }
Loading…
Cancel
Save