63 lines
2.7 KiB
PHP
63 lines
2.7 KiB
PHP
<?php
|
|
// NetworkStream.php
|
|
// Created: 2021-04-30
|
|
// Updated: 2024-07-31
|
|
|
|
namespace Index\IO;
|
|
|
|
use ErrorException;
|
|
use Index\Net\IPAddress;
|
|
use Index\Net\EndPoint;
|
|
|
|
class NetworkStream extends GenericStream {
|
|
public function __construct(string $hostname, int $port, float|null $timeout) {
|
|
try {
|
|
$stream = fsockopen($hostname, $port, $errcode, $errmsg, $timeout);
|
|
} catch(ErrorException $ex) {
|
|
throw new IOException('An error occurred while trying to connect.', $ex->getCode(), $ex);
|
|
}
|
|
|
|
if($stream === false)
|
|
throw new IOException('An unhandled error occurred while trying to connect.');
|
|
|
|
parent::__construct($stream);
|
|
}
|
|
|
|
public function setBlocking(bool $blocking): void {
|
|
stream_set_blocking($this->stream, $blocking);
|
|
}
|
|
|
|
public static function openEndPoint(EndPoint $endPoint, float|null $timeout = null): NetworkStream {
|
|
return new NetworkStream((string)$endPoint, -1, $timeout);
|
|
}
|
|
public static function openEndPointSSL(EndPoint $endPoint, float|null $timeout = null): NetworkStream {
|
|
return new NetworkStream('ssl://' . ((string)$endPoint), -1, $timeout);
|
|
}
|
|
public static function openEndPointTLS(EndPoint $endPoint, float|null $timeout = null): NetworkStream {
|
|
return new NetworkStream('tls://' . ((string)$endPoint), -1, $timeout);
|
|
}
|
|
|
|
public static function openHost(string $hostname, int $port, float|null $timeout = null): NetworkStream {
|
|
return new NetworkStream($hostname, $port, $timeout);
|
|
}
|
|
public static function openHostSSL(string $hostname, int $port, float|null $timeout = null): NetworkStream {
|
|
return new NetworkStream('ssl://' . ((string)$hostname), $port, $timeout);
|
|
}
|
|
public static function openHostTLS(string $hostname, int $port, float|null $timeout = null): NetworkStream {
|
|
return new NetworkStream('tls://' . ((string)$hostname), $port, $timeout);
|
|
}
|
|
|
|
public static function openAddress(IPAddress $address, int $port, float|null $timeout = null): NetworkStream {
|
|
return new NetworkStream($address->getAddress(), $port, $timeout);
|
|
}
|
|
public static function openAddressSSL(IPAddress $address, int $port, float|null $timeout = null): NetworkStream {
|
|
return new NetworkStream('ssl://' . $address->getAddress(), $port, $timeout);
|
|
}
|
|
public static function openAddressTLS(IPAddress $address, int $port, float|null $timeout = null): NetworkStream {
|
|
return new NetworkStream('tls://' . $address->getAddress(), $port, $timeout);
|
|
}
|
|
|
|
public static function openUnix(string $path, float|null $timeout = null): NetworkStream {
|
|
return new NetworkStream('unix://' . ((string)$path), -1, $timeout);
|
|
}
|
|
}
|