router = $this->collector->get('wss'); } /** * @return void * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface * @throws ConfigException */ public function init(): void { $exception = Config::get('exception.websocket', ExceptionHandlerDispatcher::class); if (!in_array(ExceptionHandlerInterface::class, class_implements($exception))) { $exception = ExceptionHandlerDispatcher::class; } $this->exception = $this->container->get($exception); } /** * @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()); $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 { $executor = $handler->dispatch->handler; if (Context::inCoroutine()) { $response->upgrade(); if ($handler instanceof OnHandshakeInterface) { $handler->OnHandshake($request, $response); } if ($executor instanceof OnOpenInterface) { $executor->OnOpen($request); } while (true) { $frame = $response->recv(); if ($frame === false || $frame instanceof CloseFrame || $frame === '') { $handler->OnClose($response->fd); break; } $handler->OnMessage($frame); } } else { $this->OnOpen($request); } } } catch (\Throwable $throwable) { $psrResponse = $this->exception->emit($throwable, di(CResponse::class)); } finally { $this->emitter->sender($response, $psrResponse); } } /** * @param Frame $frame * @return void */ public function OnMessage(Frame $frame): void { } /** * @param int $fd * @return void */ public function OnClose(int $fd): void { } /** * @param int $fd * @return void */ public function OnDisconnect(int $fd): void { // TODO: Implement OnDisconnect() method. } /** * @param Request $request * @return void */ public function OnOpen(Request $request): void { } }