调用 server()->help();
17331
public function help()
    {
        //获取显示模板
        $tpl = \Grace\Base\Help::getplframe();

        //oblist
        $objectList = $this->objectList();

        $chr = $title = $_GET['chr'];

        //计算左侧菜单
        //<li  class="active"><a href="/index.php?book=01-grace&lm=controller&ar=controller.md"> Controller </a></li>
        $nav = '';
        foreach ($objectList as $key => $value) {
            if ($key == $chr) {
                $nav .= "<li  class=\"active\"><a href=\"?chr=$key\"> $key </a></li>";
            } else {
                $nav .= "<li><a href=\"?chr=$key\"> $key </a></li>";
            }
        }

        $nr = '';
        if ($objectList[$chr]) {
            //获取内容
            $file = $objectList[$chr];
            $nr = (new \Parsedown())->text(file_get_contents(__DIR__ . '/' . $file));

        } else {
            $nr = '';
        }

        $html = str_replace('##nav##', $nav, $tpl);
        $html = str_replace('##nr##', $nr, $html);
        $html = str_replace('##title##', $title, $html);
        echo $html;
        exit;
    }
187329
private function parseNetwork()
    {
        // 用户名密码处理
        $username = $this->request->getAttribute('username');
        if(null != $username)
        {
            $userPwd = $username . ':' . $this->request->getAttribute('password', '');
        }
        else
        {
            $userPwd = '';
        }
        curl_setopt_array($this->handler, array(
            // 连接超时
            CURLOPT_CONNECTTIMEOUT_MS       => $this->request->getAttribute('connectTimeout', 30000),
            // 总超时
            CURLOPT_TIMEOUT_MS              => $this->request->getAttribute('timeout', 0),
            // 下载限速
            CURLOPT_MAX_RECV_SPEED_LARGE    => $this->request->getAttribute('downloadSpeed'),
            // 上传限速
            CURLOPT_MAX_SEND_SPEED_LARGE    => $this->request->getAttribute('uploadSpeed'),
            // 连接中用到的用户名和密码
            CURLOPT_USERPWD                 => $userPwd,
        ));
    }
288336
function dispatch(\swoole_server $server ,string $data, ...$args):void
    {
        $clientIp = null;
        $type = $this->config->getType();
        switch ($type){
            case Config::TCP:{
                $client = new Tcp( ...$args);
                break;
            }
            case Config::WEB_SOCKET:{
                $client = new WebSocket( ...$args);
                break;
            }
            case Config::UDP:{
                $client = new Udp( ...$args);
                break;
            }
            default:{
                throw new \Exception('dispatcher type error : '.$type);
            }
        }
        $caller = null;
        $response = new Response();
        try{
            $caller = $this->config->getParser()->decode($data,$client);
        }catch (\Throwable $throwable){
            //注意，在解包出现异常的时候，则调用异常处理，默认是断开连接，服务端抛出异常
            $this->hookException($server,$throwable,$data,$client,$response);
            goto response;
        }
        //如果成功返回一个调用者，那么执行调用逻辑
        if($caller instanceof Caller){
            $caller->setClient($client);
            //解包正确
            $controllerClass = $caller->getControllerClass();
            try{
                $controller = $this->getController($controllerClass);
            }catch (\Throwable $throwable){
                $this->hookException($server,$throwable,$data,$client,$response);
                goto response;
            }
            if($controller instanceof Controller){
                try{
                    $controller->__hook( $server,$this->config, $caller, $response);
                }catch (\Throwable $throwable){
                    $this->hookException($server,$throwable,$data,$client,$response);
                }finally {
                    $this->recycleController($controllerClass,$controller);
                }
            }else{
                $throwable = new ControllerPoolEmpty('controller pool empty for '.$controllerClass);
                $this->hookException($server,$throwable,$data,$client,$response);
            }
        }
        response :{
            switch ($response->getStatus()){
                case Response::STATUS_OK:{
                    $this->response($server,$client,$response);
                    break;
                }
                case Response::STATUS_RESPONSE_AND_CLOSE:{
                    $this->response($server,$client,$response);
                    $this->close($server,$client);
                    break;
                }
                case Response::STATUS_CLOSE:{
                    $this->close($server,$client);
                    break;
                }
            }
        }
    }
1248121
protected function doRouteAfter()
    {
        // 记录匹配的路由信息
        $option = $this->rule->getOption();
        $matches = $this->rule->getVars();

        // 绑定模型数据
        if (!empty($option['model'])) {
            $this->createBindModel($option['model'], $matches);
        }

        // 指定Header数据
        if (!empty($option['header'])) {
            $header = $option['header'];
            $this->app['hook']->add('response_send', function ($response) use ($header) {
                $response->header($header);
            });
        }

        // 指定Response响应数据
        if (!empty($option['response'])) {
            foreach ($option['response'] as $response) {
                $this->app['hook']->add('response_send', $response);
            }
        }

        // 开启请求缓存
        if (isset($option['cache']) && $this->request->isGet()) {
            $this->parseRequestCache($option['cache']);
        }

        if (!empty($option['append'])) {
            $this->request->setRouteVars($option['append']);
        }
    }
337483
function portIsOccupied(port, callback) {
    // 创建服务并监听该端口
    const server = net.createServer().listen(port);

    server.on('listening', function () { // 执行这块代码说明端口未被占用
        server.close(); // 关闭服务
        // console.log('The port【' + port + '】 is available.'); // 控制台输出信息

        if (typeof callback === 'function') {
            callback(true);
        }
    });

    server.on('error', function (err) {
        if (err.code === 'EADDRINUSE') { // 端口已经被使用
            // console.log('The port【' + port + '】 is occupied, please change other port.');
        }

        if (typeof callback === 'function') {
            callback(false, err);
        }
    });
}
686059
function getServer($servers)
    {
        if (empty($servers))
        {
            throw new \Exception("servers config empty.");
        }

        if ($this->keepSocket)
        {
            if (is_array($this->keepSocketServer) && count($this->keepSocketServer))
            {
                return $this->keepSocketServer;
            }
            else
            {
                $this->keepSocketServer = Tool::getServer($servers);

                return $this->keepSocketServer;
            }
        }

        //保留老的server获取方式
        return Tool::getServer($servers);
    }
1055446
function(domain, ip, groupName, target_groupName) {
		this._batchHost(function(hostsobject) {
			var group = hostsobject[groupName];
			var t_group = hostsobject[target_groupName] = hostsobject[target_groupName] || [];
			if (group) {
				var host, move, i;
				//目标分组里是否存在该条host，若存在则不作处理。
				for (i = 0; i < t_group.length; i++) {
					host = t_group[i];
					if (host.domain === domain && host.ip === ip) {
						return false;
					}
				}
				for (i = 0; i < group.length; i++) {
					host = group[i];
					if (host.domain === domain && host.ip === ip) {
						t_group.push(host);
						group.splice(i, 1);
						break;
					}
				}
				return hostsobject;
			}
		});
	}
237821
@Override
	protected void initServer(TServerTransport serverTransport) {
		ThriftServerConfiguration configuration = getServerConfiguration();
		// 使用多线程半同步半异步方式
		TThreadedSelectorServer.Args args = new TThreadedSelectorServer.Args((TNonblockingServerSocket) serverTransport)
				.transportFactory(configuration.getTransportFactory())
				.protocolFactory(configuration.getProtocolFactory());
		if (configuration.getExecutorService() != null)
			args.executorService(configuration.getExecutorService());
		server = new TThreadedSelectorServer(
				configuration.getServerArgsAspect().tThreadedSelectorServerArgsAspect(args).processor(getProcessor()));
		if (configuration.getServerEventHandler() != null)
			server.setServerEventHandler(configuration.getServerEventHandler());
	}
1003588
public function start()
    {
        $httpServer = $this->getHttpServer();

        // 是否正在运行
        if ($httpServer->isRunning()) {
            $serverStatus = $httpServer->getServerSetting();

            \output()->writeln("<error>The server have been running!(PID: {$serverStatus['masterPid']})</error>", true, true);
        } else {
            $serverStatus = $httpServer->getServerSetting();
        }

        // 启动参数
        $this->setStartArgs($httpServer);
        $httpStatus = $httpServer->getHttpSetting();
        $tcpStatus = $httpServer->getTcpSetting();

        // Setting
        $workerNum = $httpServer->setting['worker_num'];

        // HTTP 启动参数
        $httpHost = $httpStatus['host'];
        $httpPort = $httpStatus['port'];
        $httpMode = $httpStatus['mode'];
        $httpType = $httpStatus['type'];

        // TCP 启动参数
        $tcpEnable = $serverStatus['tcpable'];
        $tcpHost = $tcpStatus['host'];
        $tcpPort = $tcpStatus['port'];
        $tcpType = $tcpStatus['type'];
        $tcpEnable = $tcpEnable ? '<info>Enabled</info>' : '<warning>Disabled</warning>';

        // 信息面板
        $lines = [
            '                         Server Information                      ',
            '********************************************************************',
            "* HTTP | host: <note>$httpHost</note>, port: <note>$httpPort</note>, type: <note>$httpType</note>, worker: <note>$workerNum</note>, mode: <note>$httpMode</note>",
            "* TCP  | host: <note>$tcpHost</note>, port: <note>$tcpPort</note>, type: <note>$tcpType</note>, worker: <note>$workerNum</note> ($tcpEnable)",
            '********************************************************************',
        ];

        // 启动服务器
        \output()->writeln(implode("\n", $lines));
        $httpServer->start();
    }
429831
public function init()
    {
        /**
         * 设置默认时区
         */
        if ($this->timezone)
        {
            date_default_timezone_set($this->timezone);
        }

        /**
         * 设置地区信息（地域信息）
         */
        if ($this->locale)
        {
            setlocale(LC_ALL, $this->locale);
        }

        if ($this->charset && function_exists('mb_internal_encoding'))
        {
            mb_internal_encoding($this->charset);
        }

        /**
         * 当输入字符的编码是无效的，或者字符代码不存在于输出的字符编码中时，可以为其指定一个替代字符。
         *
         * @link http://www.php.net/manual/function.mb-substitute-character.php
         */
        mb_substitute_character('none');

        // 确保输入的数据安全
        $_GET = Security::sanitize($_GET);
        $_POST = Security::sanitize($_POST);
        $_COOKIE = Security::sanitize($_COOKIE);

        self::cleanComponents();
    }
198419
async def grant(self, user_id, *permissions):
        "  "

        prefix = f"{self._prefix_perm}/{user_id}/"

        perm_names = [str(p) for p in permissions]        
        checkings = [
            KV.put.txn(prefix + p, b'\0', prev_kv=True) for p in perm_names
        ]
        success, response = await self._client.txn(compare=[], success=checkings)
        if not success:
            errmsg = f"无法授予用户({user_id})的权限: {{{', '.join(perm_names)}}}"
            raise Unprocessable(errmsg)

        if logger.isEnabledFor(logging.DEBUG):
            granted, ignored = set(), set()
            for i, (perm, _)  in enumerate(response):
                if perm is None:
                    granted.add(perm_names[i])
                else:
                    ignored.add(perm_names[i])
            
            logger.debug(f"授予用户({user_id})权限({', '.join(granted)}), "
                            f"忽略已授权({', '.join(ignored)})")
888900
function launch(){

        $this->waitAnswer();
        $template = $this->getHomeCard();
        $server = self::$servers[array_rand(self::$servers)];
        $speech = '欢迎使用平台样例演示，请试着说' . $server;
        $reprompt = '没有听懂，可以直接对我想要使用的服务，例如' . $server;
        $hint = new Hint($server);

        return [
            'outputSpeech' => $speech,
            'reprompt' => $reprompt,
            'directives' => [$hint, $template]
        ];
    }
1362905
public void start() throws IkasoaException {
		if (server == null) {
			log.debug("Server configuration : {}", configuration);
			// 不允许使用1024以内的端口.
			if (!ServerUtil.isSocketPort(serverPort))
				throw new IkasoaException(String.format(
						"Server initialize failed ! Port range must is 1025 ~ 65535 . Your port is : %d .",
						serverPort));
			try {
				initServer(getTransport());
			} catch (TTransportException e) {
				throw new IkasoaException("Server initialize failed !", e);
			}
		}
		// 如果服务没有启动,则自动启动服务.
		if (server != null) {
			if (server.isServing()) {
				log.info("Server already run .");
				return;
			}
			server.serve();
			log.info("Startup server ... (name : {} , port : {})", getServerName(), getServerPort());
		} else
			log.warn("Startup server failed !");
	}
74549
protected void checkParameters() {
        // 检查注入的ref是否接口实现类
        Class proxyClass = providerConfig.getProxyClass();
        String key = providerConfig.buildKey();
        T ref = providerConfig.getRef();
        if (!proxyClass.isInstance(ref)) {
            throw ExceptionUtils.buildRuntime("provider.ref",
                ref == null ? "null" : ref.getClass().getName(),
                "This is not an instance of " + providerConfig.getInterfaceId()
                    + " in provider config with key " + key + " !");
        }
        // server 不能为空
        if (CommonUtils.isEmpty(providerConfig.getServer())) {
            throw ExceptionUtils.buildRuntime("server", "NULL", "Value of \"server\" is not specified in provider" +
                " config with key " + key + " !");
        }
        checkMethods(proxyClass);
    }
1284414
private function loadContainer(): void
    {
        $loaderClass = $this->config->getValue('SERVICE_LOADER');
        $this->container = new Container();
        $serviceLoader = new $loaderClass();
        $serviceLoader->loadContainerService($this->container);
        // 错误处理器
        $this->loadErrorHandler($this->getService('errorHandler'));
        $this->loadRouteErrorHandler($this->getService('routeErrorHandler'));
        // 路由服务
        $this->loadRouteHandler($this->getService('routeHandler'));
    }
677525
public function init(){
		$table_definition = $this->exdb->get_table_definition_all();
		// var_dump($table_definition);
		$error = array();
		foreach($table_definition->tables as $table_name=>$table_definition_row){
			// var_dump($table_definition_row);

			$sql_create_db = '';
			$sql_create_db .= 'CREATE TABLE '.$this->exdb->get_physical_table_name($table_definition_row->name).' (';
			$ary_table_columns = array();
			$ary_foreign_keys = array();
			foreach( $table_definition_row->columns as $column_definition ){
				$sql_column_definition = '';

				// セル名
				$sql_column_definition .= $column_definition->name;

				// 型
				switch(strtolower( $column_definition->type )){
					case 'email':
					case 'string':
					case 'password':
					case 'auto_id':
						$sql_column_definition .= ' VARCHAR';
						break;
					case 'create_date':
					case 'update_date':
					case 'delete_date':
						$sql_column_definition .= ' DATETIME';
						break;
					case 'int':
					case 'integer':
					case 'number':
					case 'auto_increment':
						$sql_column_definition .= ' INTEGER';
						break;
					case 'delete_flg':
						$sql_column_definition .= ' INTEGER';
						break;
					case 'text':
					case 'date':
					case 'datetime':
					default:
						$sql_column_definition .= ' '.strtoupper($column_definition->type);
						break;
				}

				// NOT NULL 制約
				if( @$column_definition->not_null ){
					$sql_column_definition .= ' NOT NULL';
				}

				// UNIQUE 制約
				if( @$column_definition->unique ){
					$sql_column_definition .= ' UNIQUE';
				}

				// FOREIGN KEY 制約
				if( @$column_definition->foreign_key ){
					$ary_foreign_keys[$column_definition->name] = $column_definition->foreign_key;
				}

				array_push($ary_table_columns, $sql_column_definition);
			}
			$sql_create_db .= implode($ary_table_columns, ',');

			if( count($ary_foreign_keys) ){
				// FOREIGN KEY 制約
				foreach($ary_foreign_keys as $colName=>$foreign_tbl_col){
					$sql_create_db .= ', FOREIGN KEY (';
					$sql_create_db .= $colName;
					$sql_create_db .= ')';
					$foreign_tbl_col = explode('.', $foreign_tbl_col);
					$sql_create_db .= ' REFERENCES '.$this->exdb->get_physical_table_name($foreign_tbl_col[0]).'('.$foreign_tbl_col[1].')';
				}
			}

			$sql_create_db .= ');';
			// var_dump($sql_create_db);
			$result = @$this->exdb->pdo()->query($sql_create_db);
			// var_dump($result);
			if( !$result ){
				array_push($error, '[ERROR] Failed to create table "'.$this->exdb->get_physical_table_name($table_definition_row->name).'"');
			}
		}
		// var_dump($error);
		$rtn = true;
		if(count($error)){$rtn = false;}
		return $rtn;
	}
911857
function callBack($from,$to,$customerSerNum,$fromSerNum,$promptTone)
	  {
        //子帐号鉴权信息验证，对必选参数进行判空。
        $auth=$this->subAuth();
        if($auth!=""){
            return $auth;
        }
        // 拼接请求包体
        if($this->BodyType=="json"){
           $body= "{'from':'$from','to':'$to','customerSerNum':'$customerSerNum','fromSerNum':'$fromSerNum','promptTone':'$promptTone'}";
        }else{
           $body= "<CallBack>
                     <from>$from</from>
                     <to>$to</to>
                     <customerSerNum>$customerSerNum</customerSerNum>
                     <fromSerNum>$fromSerNum</fromSerNum>
                     <promptTone>$promptTone</promptTone>
                   </CallBack>";
        }
        $this->showlog("request body = ".$body);
        // 大写的sig参数
        $sig =  strtoupper(md5($this->SubAccountSid . $this->SubAccountToken . $this->Batch));
        // 生成请求URL
        $url="https://$this->ServerIP:$this->ServerPort/$this->SoftVersion/SubAccounts/$this->SubAccountSid/Calls/Callback?sig=$sig";
        $this->showlog("request url = ".$url);
        // 生成授权：子帐号Id + 英文冒号 + 时间戳
        $authen=base64_encode($this->SubAccountSid . ":" . $this->Batch);
        // 生成包头
        $header = array("Accept:application/$this->BodyType","Content-Type:application/$this->BodyType;charset=utf-8","Authorization:$authen");
        // 发请求
        $result = $this->curl_post($url,$body,$header);
        $this->showlog("response body = ".$result);
        if($this->BodyType=="json"){//JSON格式
           $datas=json_decode($result);
        }else{ //xml格式
           $datas = simplexml_load_string(trim($result," \t\n\r"));
        }
      //  if($datas == FALSE){
//            $datas = new stdClass();
//            $datas->statusCode = '172003';
//            $datas->statusMsg = '返回包体错误'; 
//        }
        return $datas;
	}