tapi/app/command/admin/SysGateway.php
2025-08-29 17:53:12 +08:00

96 lines
3.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\command\admin;
use app\event\AdminGatewayEvents;
use GatewayWorker\Register;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use \GatewayWorker\BusinessWorker;
use Workerman\Worker;
class SysGateway extends Command
{
protected function configure()
{
$this->setName('admin:gateway')
->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
->addOption('mode', 'm', Option::VALUE_OPTIONAL, 'Run the workerman server in daemon mode.')
->setDescription('后台系统网关服务');
}
protected function execute(Input $input, Output $output)
{
$action = $input->getArgument('action');
$mode = $input->getOption('mode');
global $argv;
$argv = [];
array_unshift($argv, 'think', $action);
if ($mode == 'd') {
$argv[] = '-d';
} else if ($mode == 'g') {
$argv[] = '-g';
}
$register = $this->startRegister();
$gateway = $this->startGateway();
$worker = new BusinessWorker();
$worker->name = 'ChatBusinessWorker';
$worker->count = 4;
$worker->registerAddress = '127.0.0.1:1236';
$worker->eventHandler = AdminGatewayEvents::class;
// 运行所有服务
Worker::runAll();
}
private function startRegister(): Register
{
return new Register('text://127.0.0.1:1236');
}
private function startGateway(): \GatewayWorker\Gateway
{
// gateway 进程
$gateway = new \GatewayWorker\Gateway("Websocket://0.0.0.0:7272");
// 设置名称方便status时查看
$gateway->name = 'ChatGateway';
// 设置进程数,一般两个进程就足够
$gateway->count = 2;
// 分布式部署时请设置成内网ip非127.0.0.1
$gateway->lanIp = '127.0.0.1';
// 内部通讯起始端口。假如$gateway->count=2起始端口为2300
// 则一般会使用2300 2301 2个端口作为内部通讯端口
$gateway->startPort = 2300;
// 心跳间隔
$gateway->pingInterval = 10;
// 心跳数据
$gateway->pingData = '{"type":"ping"}';
// 服务注册地址
$gateway->registerAddress = '127.0.0.1:1236';
/*
// 当客户端连接上来时设置连接的onWebSocketConnect即在websocket握手时的回调
$gateway->onConnect = function($connection)
{
$connection->onWebSocketConnect = function($connection , $http_header)
{
// 可以在这里判断连接来源是否合法,不合法就关掉连接
// $_SERVER['HTTP_ORIGIN']标识来自哪个站点的页面发起的websocket链接
if($_SERVER['HTTP_ORIGIN'] != 'http://chat.workerman.net')
{
$connection->close();
}
// onWebSocketConnect 里面$_GET $_SERVER是可用的
// var_dump($_GET, $_SERVER);
};
};
*/
return $gateway;
}
}