SocketFactory.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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\Socket;
  12. use Hyperf\Engine\Contract\Socket\SocketFactoryInterface;
  13. use Hyperf\Engine\Contract\Socket\SocketOptionInterface;
  14. use Hyperf\Engine\Contract\SocketInterface;
  15. use Hyperf\Engine\Exception\SocketConnectException;
  16. use Hyperf\Engine\Socket;
  17. class SocketFactory implements SocketFactoryInterface
  18. {
  19. public function make(SocketOptionInterface $option): SocketInterface
  20. {
  21. $socket = new Socket(AF_INET, SOCK_STREAM, 0);
  22. if ($protocol = $option->getProtocol()) {
  23. $socket->setProtocol($protocol);
  24. }
  25. if ($option->getTimeout() === null) {
  26. $res = $socket->connect($option->getHost(), $option->getPort());
  27. } else {
  28. $res = $socket->connect($option->getHost(), $option->getPort(), $option->getTimeout());
  29. }
  30. if (! $res) {
  31. throw new SocketConnectException($socket->errMsg, $socket->errCode);
  32. }
  33. return $socket;
  34. }
  35. }