监听端口

@throws Exception
333019
public function listen()
    {
        if ( ! $this->_socketName)
        {
            Base::getLog()->error(__METHOD__ . ' missing socket name');
            return;
        }

        // 获得应用层通讯协议以及监听的地址
        $temp = explode(':', $this->_socketName, 2);
        $scheme = Arr::get($temp, 0);
        $address = Arr::get($temp, 1);
        Base::getLog()->debug(__METHOD__ . ' fetch socket info', [
            'scheme'  => $scheme,
            'address' => $address,
        ]);

        // 如果有指定应用层协议，则检查对应的协议类是否存在
        if ($scheme != 'tcp' && $scheme != 'udp')
        {
            // 判断是否有自定义协议
            if (isset(self::$protocolMapping[$scheme]) && class_exists(self::$protocolMapping[$scheme]))
            {
                $this->_protocol = self::$protocolMapping[$scheme];
            }
            elseif ($this->protocolClass && class_exists($this->protocolClass))
            {
                $this->_protocol = $this->protocolClass;
            }
            else
            {
                // 没有的话，就按照workerman那套来走
                $scheme = ucfirst($scheme);
                $this->_protocol = '\\Protocols\\' . $scheme;
                if ( ! class_exists($this->_protocol))
                {
                    $this->_protocol = "\\Workerman\\Protocols\\$scheme";
                    if ( ! class_exists($this->_protocol))
                    {
                        throw new Exception("class \\Protocols\\$scheme not exist");
                    }
                }
            }
        }
        elseif ($scheme === 'udp')
        {
            $this->transport = 'udp';
        }
        Base::getLog()->debug(__METHOD__ . ' set protocol', [
            'class' => $this->_protocol,
        ]);

        // flag
        $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
        $errNo = 0;
        $errmsg = '';
        $this->_mainSocket = stream_socket_server($this->transport . ":" . $address, $errNo, $errmsg, $flags, $this->_context);
        if ( ! $this->_mainSocket)
        {
            throw new Exception($errmsg);
        }

        // 尝试打开tcp的keepalive，关闭TCP Nagle算法
        if (function_exists('socket_import_stream'))
        {
            $socket = socket_import_stream($this->_mainSocket);
            @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
            @socket_set_option($socket, SOL_SOCKET, TCP_NODELAY, 1);
        }

        // 设置非阻塞
        stream_set_blocking($this->_mainSocket, 0);

        // 放到全局事件轮询中监听_mainSocket可读事件（客户端连接事件）
        if (self::$globalEvent)
        {
            if ($this->transport !== 'udp')
            {
                self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, [$this, 'acceptConnection']);
            }
            else
            {
                self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, [$this, 'acceptUdpConnection']);
            }
        }
    }
915638
@Override
    protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (!support.isLegal(request)) {
            return;
        }
        //设置响应编码格式
        response.setCharacterEncoding("UTF-8");
        String resp = support.processRequest(request);
        PrintWriter pw = response.getWriter();
        pw.write(resp);
        pw.flush();
        pw.close();
    }
392497
private function checkProperties()
    {
        if (!isset($this->listId)) {
            throw new \Exception('[listId] is not set', 1);
        }

        if (!isset($this->installationUrl)) {
            throw new \Exception('[installationUrl] is not set', 1);
        }

        if (!isset($this->apiKey)) {
            throw new \Exception('[apiKey] is not set', 1);
        }
    }
871019
public void start() throws Exception {
        long startTime = System.currentTimeMillis();

        HandlerCollection handlers = new HandlerCollection();
        addModulesToJetty(handlers);

        // Create the server.
        int serverPort = serverPort();
        System.out.println("**** Starting Server (" + getClass().getSimpleName() + ") on port: " + serverPort);
        server = new Server(serverPort);
        server.setHandler(handlers);
        server.start();
        long endTime = System.currentTimeMillis();
        System.out.println("******* Started in " + (endTime - startTime) + "ms");
    }
1054541
public void start() throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "start", this);

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            SibTr.debug(tc, "Start ME, mode defaulting to ME_START_DEFAULT");
        start(JsConstants.ME_START_DEFAULT);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "start");
    }
482874
private HttpResponse init() throws HttpException {
		try {
			this.status = httpConnection.responseCode();
			this.in = (this.status < HttpStatus.HTTP_BAD_REQUEST) ? httpConnection.getInputStream() : httpConnection.getErrorStream();
		} catch (IOException e) {
			if (e instanceof FileNotFoundException) {
				// 服务器无返回内容，忽略之
			} else {
				throw new HttpException(e);
			}
		}

		try {
			this.headers = httpConnection.headers();
		} catch (IllegalArgumentException e) {
			StaticLog.warn(e, e.getMessage());
		}
		final Charset charset = httpConnection.getCharset();
		this.charsetFromResponse = charset;
		if (null != charset) {
			this.charset = charset;
		}

		if (null == this.in) {
			// 在一些情况下，返回的流为null，此时提供状态码说明
			this.in = new ByteArrayInputStream(StrUtil.format("Error request, response status: {}", this.status).getBytes());
		} else if (isGzip() && false == (in instanceof GZIPInputStream)) {
			try {
				in = new GZIPInputStream(in);
			} catch (IOException e) {
				// 在类似于Head等方法中无body返回，此时GZIPInputStream构造会出现错误，在此忽略此错误读取普通数据
				// ignore
			}
		} else if (isDeflate() && false == (in instanceof DeflaterInputStream)) {
			//Accept-Encoding: defalte
			in = new DeflaterInputStream(in);
		}

		// 同步情况下强制同步
		return this.isAsync ? this : forceSync();
	}
1196718
public void start(CockroachQueue queue) throws Exception {
        this.thread = config.getThread();
        TaskResponseFilterBox filterBox = this.bulidResponseFilters();
        this.executerListeners.forEach(IExecutersListener::onStart);
        for (int i = 0; i < thread; i++) {
            TaskExecuter executer = new TaskExecuter(
                    queue,
                    this.bulidHttpClient(),
                    this.config.getStore().newInstance(),
                    new TaskErrorHandlerBox().add(this.config.getTaskErrorHandler().newInstance()),
                    this.config.getThreadSleep(),
                    this.config.isAutoClose(),
                    filterBox
            );
            logger.info("new thread:" + executer.getId());
            service.execute(executer);
            executerList.add(executer);
        }
        /**
         * 不可以再继续 提交新的任务 已经提交的任务不影响
         */
        service.shutdown();

        /**
         * 每 5 秒检测是否全部线程执行完毕
         */
        new Thread(() -> {
            try {
                while (true) {
                    TimeUnit.SECONDS.sleep(5);
                    if (service.isTerminated()) {
                        logger.info("任务已经全部执行完毕");
                        this.executerListeners.forEach(IExecutersListener::onEnd);
                        break;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
224534
public function multiInit()
    {
        //domain > url
        $host = $this->env->get('HTTP_HOST');
        $apps = [];
        if (isset($this->multiApps[$host])) {
            $apps = $this->multiApps[$host];
        }
        $defapps = isset($this->multiApps['default']) ? $this->multiApps['default'] : [];
        if (!$apps && !$defapps) {
            throw new Exception("无法找到设置的初始化映射规则");
        }
        $app = null;
        $dir = null;
        $setting = [];
        $middleware = null;
        if ($apps) {
            $_apps = $this->getAppConfig($apps);
            if ($_apps) {
                list($app, $dir, $setting, $middleware) = $_apps;
            }
        } else {
            $_apps = $this->getAppConfig($defapps);
            if ($_apps) {
                list($app, $dir, $setting, $middleware) = $_apps;
            }
        }
        //开始处理新的路由
        if ($app === null) {
            if ($this->getConfig('debug')) {
                throw new Exception('无法找到请求的处理方法');
            } else {
                $this->route->notFound();
            }
        }
        $this->init($app, $dir, $setting, $middleware);
        //注册其他应用的自动加载
        foreach ($this->multiApps as $apps) {
            if (!$apps) {
                continue;
            }
            foreach ($apps as $_app) {
                list($appname, $_dir) = $_app;
                if ($app != $appname) {
                    $namespace = $appname;
                    $this->loader->addNamespace('\\' . $namespace, $_dir . '/' . $appname . '/');
                }
                $this->setInitApps($appname, $_dir);
            }
        }
        return $app;
    }
605933
private function invokeRoute(): void
    {
        $moduleName = $this->routeInfo->moduleName;
        $controllerName = $this->routeInfo->controllerName;
        $actionName = $this->routeInfo->actionName;
        $controllerClass = $this->config->getValue('CONTROLLER_NAMESPACE') . '\\' . str_replace('.', '\\', $moduleName) . '\\' . $controllerName;
        if (! class_exists($controllerClass)) {
            $event = RouteErrorEvent::createCustom(404, $moduleName . '/' . $controllerName . '/' . $actionName . '对应的控制器类' . $controllerClass . '不存在');
            $event->httpErrorCode = 404;
            $this->dispatchEvent($event);
            return;
        }
        // 执行操作
        $this->invokeAction(new $controllerClass(), $actionName);
    }
111658
public void delete(Object po) throws Exception{
		
		SqlParamsPairs sqlAndParams = ModelSqlUtils.getDeleteFromObject(po);
		//动态切换库名
		String sql = sqlAndParams.getSql();
		
		getProxy().update(sql, sqlAndParams.getParams());	
	}
674467
public function merged()
    {
        if (!$this->openapi) {
            throw new Exception('No openapi target set. Run the MergeIntoOpenApi processor');
        }
        $unmerged = $this->openapi->_unmerged;
        $this->openapi->_unmerged = [];
        $analysis = new Analysis([$this->openapi]);
        $this->openapi->_unmerged = $unmerged;

        return $analysis;
    }
737706
final public function begin()
    {
        if (!$this->pdo) {
            throw  new Exception('您还没有连接数据库', Exception::CODE_DATABASE_ERROR);
        }
        if ($this->_begintransaction) {
            throw new Exception("已经开启了一个事务，请勿重新开启", Exception::CODE_DATABASE_ERROR);
        }
        $this->pdo->beginTransaction();
        $this->_begintransaction = true;
        return $this;
    }
898615
public function verify()
    {
        $data = $_POST;
        $sign = $data['sign'];
        unset($data['sign_type']);

        if (Helper::verify($data, $sign) === false) {
            throw new \Exception('支付宝异步通知验签失败');
        }

        foreach ($data as &$value) {
            $value = mb_convert_encoding($value, 'utf-8', $data['charset'] ? $data['charset'] : 'gb2312');
        }
        return $data;
    }
757702
public function connect()
	{
		$request  = $this->sendRequest($this->baseUrl."/auth", array('username' => $this->login, 'password' => $this->password), 2);

		$response = json_decode($request['body'], true);
		if (array_key_exists('error', $response))
		{
			throw new \Exception('Erreur '.$response['code'].' : '.$response['error']);
		} else {
			$this->token = $response['token'];
			$this->saveToken();
		}
	}
1311668
public function execute()
    {
        $this->_setOptions();

        $sResponse = $this->_execute();
        $this->_saveStatusCode();

        $iCurlErrorNumber = $this->_getErrorNumber();

        $this->_close();

        if ($iCurlErrorNumber) {
            $host = $this->getUrl();
            $parameters = http_build_query($this->getParameters(), "", "&");
            $message = $this->_getErrorMessage($iCurlErrorNumber);
            throw new Exception("cURL failed with message '$message' when calling '$host?$parameters'");
        }

        return $sResponse;
    }
447563
public void invoke() throws ActionException {
		Integer position = interceptorPosition.get();
		if (position == null) {
			position = 0;
		}

		if (interceptors != null && position < interceptors.length) {
			//执行过滤器，递归调用本方法
			interceptorPosition.set(position + 1);
			interceptors[position].invoke(this);
		}else {
			//过滤器执行完毕，执行本体方法
			invokeActionMethod();
			// 执行了Action本体方法，说明过滤器使用完毕，清理游标防止重复执行
			resetInterceptorPosition();
		}
	}
1220187
protected function getAccessTokenFromWeChat()
    {
        $url    = sprintf(self::TOKEN_URL, $this->appId, $this->appSecret);
        $client = $this->getHttpClient();
        $client->setUrl($url);
        $client->setHeaderArray(['Content-Type: application/json']);

        if (!$client->exec()) {
            throw new Exception("error when get access token from WeChat({$url})");
        }

        $result = json_decode($client->getResponse(), true);
        if (!(isset($result['access_token']) && (isset($result['expires_in'])))) {
            throw new Exception("error result when get access token from WeChat({$url})");
        }

        return ['token' => $result['access_token'], 'expire'=> $result['expires_in']];
    }