. */ namespace SP\Util; use SP\Core\Exceptions\SPException; /** * Class Connection para crear conexiones TCP o UDP * * @package SP\Util */ final class Connection implements ConnectionInterface { /** * @var resource|false */ protected $socket; protected string $host; protected int $port; protected int $errorno = 0; protected string $errorstr = ''; /** * @param $host string El host a conectar * @param $port int El puerto a conectar */ public function __construct(string $host, int $port) { $this->host = gethostbyname($host); $this->port = $port; } /** * Obtener un socket * * @param $type int EL tipo de socket TCP/UDP * * @return resource * @throws SPException */ public function getSocket(int $type) { if ($type === self::TYPE_UDP) { $this->socket = $this->getUDPSocket(); } else { $this->socket = $this->getTCPSocket(); } if ($this->socket === false) { throw new SPException($this->getSocketError(), SPException::WARNING); } stream_set_timeout($this->socket, self::SOCKET_TIMEOUT); return $this->socket; } /** * Obtener un socket del tipo UDP * * @return resource */ private function getUDPSocket() { return stream_socket_client( 'udp://'.$this->host.':'.$this->port, $this->errorno, $this->errorstr, self::SOCKET_TIMEOUT ); } /** * Obtener un socket del tipo TCP * * @return resource */ private function getTCPSocket() { return stream_socket_client( 'tcp://'.$this->host.':'.$this->port, $this->errorno, $this->errorstr, self::SOCKET_TIMEOUT ); } /** * Obtener el último error del socket */ public function getSocketError(): string { return sprintf('%s (%d)', $this->errorstr, $this->errorno); } /** * Cerrar el socket */ public function closeSocket() { fclose($this->socket); } /** * Enviar un mensaje al socket * * @throws SPException */ public function send(string $message): int { if (!is_resource($this->socket)) { throw new SPException(__u('Socket not initialized'), SPException::WARNING); } $nBytes = @fwrite($this->socket, $message); if ($nBytes === false) { throw new SPException(__u('Error while sending the data'), SPException::WARNING, $this->getSocketError()); } return $nBytes; } }