Server.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Engine\Http;
  12. use Hyperf\Engine\Contract\Http\ServerInterface;
  13. use Hyperf\Engine\Coroutine;
  14. use Hyperf\HttpMessage\Server\Request;
  15. use Psr\Log\LoggerInterface;
  16. use Swoole\Coroutine\Http\Server as HttpServer;
  17. use Throwable;
  18. class Server implements ServerInterface
  19. {
  20. public string $host;
  21. public int $port;
  22. /**
  23. * @var callable
  24. */
  25. protected $handler;
  26. protected HttpServer $server;
  27. public function __construct(protected LoggerInterface $logger)
  28. {
  29. }
  30. public function bind(string $name, int $port = 0): static
  31. {
  32. $this->host = $name;
  33. $this->port = $port;
  34. $this->server = new HttpServer($name, $port, reuse_port: true);
  35. return $this;
  36. }
  37. public function handle(callable $callable): static
  38. {
  39. $this->handler = $callable;
  40. return $this;
  41. }
  42. public function start(): void
  43. {
  44. $this->server->handle('/', function ($request, $response) {
  45. Coroutine::create(function () use ($request, $response) {
  46. try {
  47. $handler = $this->handler;
  48. $handler(Request::loadFromSwooleRequest($request), $response);
  49. } catch (Throwable $exception) {
  50. $this->logger->critical((string) $exception);
  51. }
  52. });
  53. });
  54. $this->server->start();
  55. }
  56. public function close(): bool
  57. {
  58. $this->server->shutdown();
  59. return true;
  60. }
  61. }