router = $this->collector->get('wss'); } /** * @return void * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface * @throws ConfigException */ public function init(): void { $exception = Config::get('exception.http', ExceptionHandlerDispatcher::class); if (!in_array(ExceptionHandlerInterface::class, class_implements($exception))) { $exception = ExceptionHandlerDispatcher::class; } $this->exception = $this->container->get($exception); $this->handler = $this->router->find('/', 'GET'); } /** * @param Request $request * @param Response $response * @return void * @throws Exception */ public function onHandshake(Request $request, Response $response): void { try { /** @var \Kiri\Message\Response $psrResponse */ $psrResponse = Context::setContext(ResponseInterface::class, new \Kiri\Message\Response()); /** @var ServerRequest $psrRequest */ $psrRequest = Context::setContext(RequestInterface::class, ServerRequest::createServerRequest($request)); $handler = $this->router->find('/', 'GET'); if (is_integer($handler)) { $psrResponse->withContent('Allow Method[' . $request->getMethod() . '].')->withStatus(405); } else if (is_null($handler)) { $psrResponse->withContent('Page not found.')->withStatus(404); } else { $psrResponse = $this->dispatcher->with($handler)->handle($psrRequest); $executor = $handler->callback; $response->upgrade(); if ($handler instanceof OnHandshakeInterface) { $statusCode = $handler->onHandshake($request, $response); $response->setStatusCode($statusCode); $response->write("connect ok."); } if ($executor instanceof OnOpenInterface) { $executor->onOpen($this->server, $request); } while (true) { $frame = $response->recv(); if ($frame === false || $frame instanceof CloseFrame || $frame === '') { $handler->onClose($this->server, $response->fd); break; } $handler->onMessage($this->server, $frame); } } } catch (\Throwable $throwable) { $psrResponse = $this->exception->emit($throwable, di(CResponse::class)); } finally { $this->emitter->sender($response, $psrResponse); } } /** * @param WsServer|Coroutine\Http\Server $server * @param Frame $frame * @return void */ public function onMessage(WsServer|WhServer $server, Frame $frame): void { $handler = $this->handler->callback; if ($handler instanceof OnMessageInterface) { $handler->onMessage($server, $frame); } } /** * @param WsServer|Coroutine\Http\Server $server * @param int $fd * @return void */ public function onClose(WsServer|WhServer $server, int $fd): void { $handler = $this->handler->callback; if ($handler instanceof OnCloseInterface) { $handler->onClose($server, $fd); } } /** * @param WsServer|WhServer $server * @param Request $request * @return void */ public function onOpen(WsServer|WhServer $server, Request $request): void { $handler = $this->handler->callback; if ($handler instanceof OnOpenInterface) { $handler->onOpen($server, $request); } } }