feat:gateway

START
鹿和sa0ChunLuyu 2 years ago
parent 3de0fd93db
commit f99da99405

@ -0,0 +1,21 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GatewayClient\Gateway;
use Yo;
$register = env('GATEWAY_REGISTER');
Gateway::$registerAddress = "127.0.0.1:$register";
class GatewayController extends Controller
{
public function close(Request $request)
{
$client_id = $request->post('client');
return Yo::echo([
'client_id' => $client_id
]);
}
}

@ -12,7 +12,8 @@
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^10.10",
"laravel/sanctum": "^3.2",
"laravel/tinker": "^2.8"
"laravel/tinker": "^2.8",
"workerman/gatewayclient": "^3.0"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",

23
composer.lock generated

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "aa322c53454393ed775cfe4807d54a50",
"content-hash": "bf594492c6a4c951789cc15ff31c1a5a",
"packages": [
{
"name": "brick/math",
@ -4146,6 +4146,27 @@
"validate"
],
"time": "2022-06-03T18:03:27+00:00"
},
{
"name": "workerman/gatewayclient",
"version": "v3.0.14",
"dist": {
"type": "zip",
"url": "https://mirrors.cloud.tencent.com/repository/composer/workerman/gatewayclient/v3.0.14/workerman-gatewayclient-v3.0.14.zip",
"reference": "4362468d68251015b2b385c310252afb4d6648ed",
"shasum": ""
},
"type": "library",
"autoload": {
"psr-4": {
"GatewayClient\\": "./"
}
},
"license": [
"MIT"
],
"homepage": "http://www.workerman.net",
"time": "2021-11-29T07:03:50+00:00"
}
],
"packages-dev": [

@ -0,0 +1,5 @@
/vendor
composer.lock
/.idea
/.vscode

@ -0,0 +1,139 @@
<?php
require_once __DIR__ . '/Tool.php';
class Db
{
public $db;
private static $instance = array();
public function __construct($data)
{
$dsn = "mysql:dbname=" . $data['dbname'] . ";host=" . $data['dbhost'];
$this->db = new \PDO($dsn, $data['dbuser'], $data['dbpassword']);
$this->db->query('set character set utf8mb4;');
$this->db->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
}
public static function get($key = ''): Db
{
$database['dbname'] = Tool::ini($key . 'DB_DATABASE');
$database['dbuser'] = Tool::ini($key . 'DB_USERNAME');
$database['dbpassword'] = Tool::ini($key . 'DB_PASSWORD');
$database['dbhost'] = Tool::ini($key . 'DB_HOST');
if (!isset(self::$instance[$database['dbname']]) || !self::$instance[$database['dbname']] instanceof self) {
self::$instance[$database['dbname']] = new Db($database);
} else {
try {
//断线重连
self::$instance[$database['dbname']]->db->getAttribute(\PDO::ATTR_SERVER_INFO);
} catch (\PDOException $e) {
if (strpos($e->getMessage(), 'MySQL server has gone away') !== false) {
self::$instance[$database['dbname']] = new Db($database);
}
}
}
return self::$instance[$database['dbname']];
}
/*********PDO**********/
public function count($sql, $parameters = null): int
{
return $this->exeupdate($sql, $parameters);
}
public function querysql($sql, $parameters = null)
{
return $this->exeupdate($sql, $parameters);
}
public function querysqlinsertid($sql, $parameters = null)
{
if ($this->exeupdate($sql, $parameters)) {
return $this->db->lastInsertId();
} else {
return 0;
}
}
public function getRow($sql, $parameters = null)
{
$res = $this->exequery($sql, $parameters);
if (count($res) > 0) {
return $res[0];
} else {
return array();
}
}
public function getAll($sql, $parameters = null)
{
$res = $this->exequery($sql, $parameters);
if (count($res) > 0) {
return $res;
} else {
return array();
}
}
public function beginTransaction()
{
$this->db->beginTransaction();
}
public function rollback()
{
$this->db->rollback();
}
public function commit()
{
$this->db->commit();
}
public function exequery($sql, $parameters = null)
{
$conn = $this->db;
$stmt = $conn->prepare($sql);
$stmt->execute($parameters);
$rs = $stmt->fetchall(\PDO::FETCH_ASSOC);
$stmt = null;
$conn = null;
return $rs;
}
public function exeupdate($sql, $parameters = null)
{
$stmt = $this->db->prepare($sql);
$stmt->execute($parameters);
$affectedrows = $stmt->rowcount();
$stmt = null;
$conn = null;
return $affectedrows;
}
public function checklink()
{
$res = $this->db->getAttribute(\PDO::ATTR_SERVER_INFO);
if (strpos($res, 'server has gone away') !== false) {
$this->db = null;
return false;
} else {
return true;
}
}
public function getinsertid()
{
return $this->db->lastInsertId();
}
public function close()
{
return $this->db = null;
}
}

@ -0,0 +1,42 @@
<?php
class Db2
{
public static function i($db, $table, $array)
{
$insertArr = array();
$sql = "insert into `{$table}`(";
$sql1 = 'values(';
foreach ($array as $key => $value) {
$sql .= "`{$key}`,";
$sql1 .= "?,";
$insertArr[] = $value;
}
$sql = trim($sql, ',');
$sql1 = trim($sql1, ',');
$sql .= ")" . $sql1 . ")";
$db->querysql($sql, $insertArr);
return $db->getinsertid();
}
public static function u($db, $table, $array, $where, $where_a = [])
{
$updateArr = array();
$sql = "update `{$table}` set ";
foreach ($array as $key => $value) {
$sql .= "`{$key}`=?,";
$updateArr[] = $value;
}
$sql = trim($sql, ',');
$where = ' ' . $where;
$sql .= $where;
$updateArr = array_merge($updateArr, $where_a);
return $db->querysql($sql, $updateArr);
}
public static function d($db, $table, $where, $where_a = [])
{
$sql = "delete from `{$table}` " . $where;
$db->querysql($sql, $where_a);
}
}

@ -0,0 +1,88 @@
<?php
class Tool
{
public static $env = null;
// region 获取 UUID
public static function uuid($break = '-'): string
{
$chars = md5(uniqid(mt_rand(), true));
$chars_arr = [
substr($chars, 0, 8),
substr($chars, 8, 4),
substr($chars, 12, 4),
substr($chars, 16, 4),
substr($chars, 20, 12),
];
return implode($break, $chars_arr);
}
// endregion
// region 发送POST请求
public static function post($url, $data = [], $decode = true, $type = 'json')
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
if ($type === 'data') {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
}
if ($type === 'json') {
$data_string = json_encode($data, JSON_UNESCAPED_UNICODE);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($data_string)
]);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
}
$r = curl_exec($curl);
curl_close($curl);
if ($decode) {
return json_decode($r, true);
} else {
return $r;
}
}
// endregion
// region 读取 Config ini
public static function ini($key, $default = false)
{
if (!$key) return $default;
if (!self::$env) {
$config_file_path = dirname(__DIR__, 3) . '/.env';
$env_content = file_get_contents($config_file_path);
$env_ini = parse_ini_string($env_content);
self::$env = $env_ini;
}
return (isset(self::$env[$key])) ? self::$env[$key] : $default;
}
// endregion
// region 10位时间戳 格式化
public static function date($time = false, $format = "Y-m-d H:i:s")
{
if (!$time) $time = time();
return date($format, $time);
}
// endregion
// region 去除空格
public static function ge($str)
{
return preg_replace("/\s+/", ' ', $str);
}
// endregion
// region 毫秒时间戳
public static function time()
{
return floor(microtime(true) * 1000);
}
// endregion
}

@ -0,0 +1,98 @@
<?php
/**
* This file is part of workerman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* 用于检测业务代码死循环或者长时间阻塞等问题
* 如果发现业务卡死可以将下面declare打开去掉//注释并执行php start.php reload
* 然后观察一段时间workerman.log看是否有process_timeout异常
*/
//declare(ticks=1);
require_once __DIR__ . '/../../Applications/Lib/Tool.php';
require_once __DIR__ . '/../../Applications/Lib/Db.php';
require_once __DIR__ . '/../../Applications/Lib/Db2.php';
date_default_timezone_set(Tool::ini('TIMEZONE'));
use \GatewayWorker\Lib\Gateway;
/**
* 主逻辑
* 主要是处理 onConnect onMessage onClose 三个方法
* onConnect 和 onClose 如果不需要可以不用实现并删除
*/
class Events
{
/**
* 当客户端连接时触发
* 如果业务不需此回调可以删除onConnect
*
* @param int $client_id 连接id
*/
public static function onConnect($client_id)
{
echo json_encode(['CONNECT', date('Y-m-d H:i:s'), $client_id], JSON_UNESCAPED_UNICODE) . "\n";
Gateway::sendToClient($client_id, json_encode([
'action' => 'init',
'client_id' => $client_id
], JSON_UNESCAPED_UNICODE));
}
/**
* 当客户端发来消息时触发
* @param int $client_id 连接id
* @param mixed $message 具体消息
*/
public static function onMessage($client_id, $message)
{
// $db = Db::get();
if ($message == Tool::ini('GATEWAY_PING')) {
echo json_encode(['PING', date('Y-m-d H:i:s'), $client_id], JSON_UNESCAPED_UNICODE) . "\n";
Gateway::sendToClient($client_id, Tool::ini('GATEWAY_PANG'));
}
}
/**
* 当用户断开连接时触发
* @param int $client_id 连接id
*/
public static function onClose($client_id)
{
echo json_encode(['CLOSE', date('Y-m-d H:i:s'), $client_id], JSON_UNESCAPED_UNICODE) . "\n";
if (!!Tool::ini('GATEWAY_CLOSE')) self::post(Tool::ini('APP_URL') . Tool::ini('GATEWAY_CLOSE'), ['client' => $client_id]);
}
public static function post($url, $data, $type = 'json')
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
if ($type === 'data') {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
}
if ($type === 'json') {
$data_string = json_encode($data, JSON_UNESCAPED_UNICODE);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($data_string)
]);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
}
$r = curl_exec($curl);
curl_close($curl);
return $r;
}
}

@ -0,0 +1,34 @@
<?php
/**
* This file is part of workerman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use \Workerman\Worker;
use \GatewayWorker\BusinessWorker;
// 自动加载类
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../Applications/Lib/Tool.php';
// bussinessWorker 进程
$worker = new BusinessWorker();
// worker名称
$worker->name = Tool::ini("APP_NAME") . 'Business';
// bussinessWorker进程数量
$worker->count = 1;
// 服务注册地址
$worker->registerAddress = '127.0.0.1:' . Tool::ini("GATEWAY_REGISTER");
// 如果不是在根目录启动则运行runAll方法
if (!defined('GLOBAL_START')) {
Worker::runAll();
}

@ -0,0 +1,63 @@
<?php
/**
* This file is part of workerman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use \Workerman\Worker;
use \GatewayWorker\Gateway;
// 自动加载类
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../Applications/Lib/Tool.php';
// gateway 进程这里使用Text协议可以用telnet测试
$url = 'websocket://0.0.0.0:' . Tool::ini('GATEWAY_PORT');
$gateway = new Gateway($url);
// gateway名称status方便查看
$gateway->name = Tool::ini('APP_NAME');
// gateway进程数
$gateway->count = 1;
// 本机ip分布式部署时使用内网ip
$gateway->lanIp = '127.0.0.1';
// 内部通讯起始端口,假如$gateway->count=4起始端口为4000
// 则一般会使用4000 4001 4002 4003 4个端口作为内部通讯端口
$gateway->startPort = Tool::ini('GATEWAY_START');
// 服务注册地址
$gateway->registerAddress = '127.0.0.1:' . Tool::ini('GATEWAY_REGISTER');
// 心跳间隔
$gateway->pingInterval = 60;
// 心跳数据
$gateway->pingData = Tool::ini('GATEWAY_PING');
/*
// 当客户端连接上来时设置连接的onWebSocketConnect即在websocket握手时的回调
$gateway->onConnect = function($connection)
{
$connection->onWebSocketConnect = function($connection , $http_header)
{
// 可以在这里判断连接来源是否合法,不合法就关掉连接
// $_SERVER['HTTP_ORIGIN']标识来自哪个站点的页面发起的websocket链接
if($_SERVER['HTTP_ORIGIN'] != 'http://kedou.workerman.net')
{
$connection->close();
}
// onWebSocketConnect 里面$_GET $_SERVER是可用的
// var_dump($_GET, $_SERVER);
};
};
*/
// 如果不是在根目录启动则运行runAll方法
if (!defined('GLOBAL_START')) {
Worker::runAll();
}

@ -0,0 +1,28 @@
<?php
/**
* This file is part of workerman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use \Workerman\Worker;
use \GatewayWorker\Register;
// 自动加载类
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../Applications/Lib/Tool.php';
// register 必须是text协议
$register = new Register('text://0.0.0.0:' . Tool::ini('GATEWAY_REGISTER'));
// 如果不是在根目录启动则运行runAll方法
if (!defined('GLOBAL_START')) {
Worker::runAll();
}

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2009-2015 walkor<walkor@workerman.net> and contributors (see https://github.com/walkor/workerman/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@ -0,0 +1,37 @@
GatewayClient
=================
`composer install`
`composer require workerman/gatewayclient`
```php
use GatewayClient\Gateway;
Gateway::$registerAddress = '127.0.0.1:3238';
Gateway::bindUid($client_id, $uid);
Gateway::joinGroup($client_id, $group_id);
Gateway::sendToUid($uid, $message);
Gateway::sendToGroup($group, $message);
Gateway::sendToAll($data);
Gateway::sendToClient($client_id, $data);
Gateway::closeClient($client_id);
Gateway::isOnline($client_id);
Gateway::bindUid($client_id, $uid);
Gateway::isUidOnline($uid);
Gateway::getClientIdByUid($uid);
Gateway::unbindUid($client_id, $uid);
Gateway::sendToUid($uid, $data);
Gateway::joinGroup($client_id, $group);
Gateway::sendToGroup($group, $data);
Gateway::leaveGroup($client_id, $group);
Gateway::getClientCountByGroup($group);
Gateway::getClientSessionsByGroup($group);
Gateway::getAllClientCount();
Gateway::getAllClientSessions();
Gateway::setSession($client_id, $session);
Gateway::updateSession($client_id, $session);
Gateway::getSession($client_id);
```

@ -0,0 +1,15 @@
{
"name" : "workerman/gateway-worker-demo",
"keywords": ["distributed","communication"],
"homepage": "http://www.workerman.net",
"license" : "MIT",
"require": {
"workerman/gateway-worker" : ">=3.0.0"
},
"autoload": {
"psr-4": {
"" : "./",
"" : "./Applications/YourApp/"
}
}
}

@ -0,0 +1,2 @@
php Applications\YourApp\start_register.php Applications\YourApp\start_gateway.php Applications\YourApp\start_businessworker.php
pause

@ -0,0 +1,37 @@
<?php
/**
* run with command
* php start.php start
*/
ini_set('display_errors', 'on');
use Workerman\Worker;
if(strpos(strtolower(PHP_OS), 'win') === 0)
{
exit("start.php not support windows, please use start_for_win.bat\n");
}
// 检查扩展
if(!extension_loaded('pcntl'))
{
exit("Please install pcntl extension. See http://doc3.workerman.net/appendices/install-extension.html\n");
}
if(!extension_loaded('posix'))
{
exit("Please install posix extension. See http://doc3.workerman.net/appendices/install-extension.html\n");
}
// 标记是全局启动
define('GLOBAL_START', 1);
require_once __DIR__ . '/vendor/autoload.php';
// 加载所有Applications/*/start.php以便启动所有服务
foreach(glob(__DIR__.'/Applications/*/start*.php') as $start_file)
{
require_once $start_file;
}
// 运行所有服务
Worker::runAll();

@ -13,6 +13,7 @@ use Illuminate\Support\Facades\Route;
|
*/
$admin_path = 'Admin';
Route::post("api/Gateway/close", [\App\Http\Controllers\GatewayController::class, 'close']);
Route::post("api/$admin_path/Config/create", [\App\Http\Controllers\ConfigController::class, 'create']);
Route::post("api/$admin_path/Config/update", [\App\Http\Controllers\ConfigController::class, 'update']);
Route::post("api/$admin_path/Config/delete", [\App\Http\Controllers\ConfigController::class, 'delete']);

Loading…
Cancel
Save