|
|
@@ -23,20 +23,12 @@ class UdpSocket
|
|
|
/** @var int */
|
|
|
protected $port;
|
|
|
/** @var resource|Socket|null */
|
|
|
- protected $socket;
|
|
|
+ protected $socket = null;
|
|
|
|
|
|
public function __construct(string $ip, int $port = 514)
|
|
|
{
|
|
|
$this->ip = $ip;
|
|
|
$this->port = $port;
|
|
|
- $domain = AF_INET;
|
|
|
- $protocol = SOL_UDP;
|
|
|
- // Check if we are using unix sockets.
|
|
|
- if ($port === 0) {
|
|
|
- $domain = AF_UNIX;
|
|
|
- $protocol = IPPROTO_IP;
|
|
|
- }
|
|
|
- $this->socket = socket_create($domain, SOCK_DGRAM, $protocol) ?: null;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -57,12 +49,34 @@ class UdpSocket
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- protected function send(string $chunk): void
|
|
|
+ /**
|
|
|
+ * @return resource|Socket
|
|
|
+ */
|
|
|
+ protected function getSocket()
|
|
|
{
|
|
|
- if (!is_resource($this->socket) && !$this->socket instanceof Socket) {
|
|
|
- throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' has been closed and can not be written to anymore');
|
|
|
+ if (null !== $this->socket) {
|
|
|
+ return $this->socket;
|
|
|
}
|
|
|
- socket_sendto($this->socket, $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
|
|
|
+
|
|
|
+ $domain = AF_INET;
|
|
|
+ $protocol = SOL_UDP;
|
|
|
+ // Check if we are using unix sockets.
|
|
|
+ if ($this->port === 0) {
|
|
|
+ $domain = AF_UNIX;
|
|
|
+ $protocol = IPPROTO_IP;
|
|
|
+ }
|
|
|
+
|
|
|
+ $this->socket = socket_create($domain, SOCK_DGRAM, $protocol) ?: null;
|
|
|
+ if (null === $this->socket) {
|
|
|
+ throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' could not be opened via socket_create');
|
|
|
+ }
|
|
|
+
|
|
|
+ return $this->socket;
|
|
|
+ }
|
|
|
+
|
|
|
+ protected function send(string $chunk): void
|
|
|
+ {
|
|
|
+ socket_sendto($this->getSocket(), $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
|
|
|
}
|
|
|
|
|
|
protected function assembleMessage(string $line, string $header): string
|