1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-07-31 18:30:15 +02:00

Allow UdpSocket to reconnect after close()

This commit is contained in:
Jordi Boggiano
2022-05-10 10:19:45 +02:00
parent c709906d0a
commit 5d43fd52d3
2 changed files with 28 additions and 16 deletions

View File

@@ -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
}
}
/**
* @return resource|Socket
*/
protected function getSocket()
{
if (null !== $this->socket) {
return $this->socket;
}
$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
{
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');
}
socket_sendto($this->socket, $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
socket_sendto($this->getSocket(), $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
}
protected function assembleMessage(string $line, string $header): string

View File

@@ -58,10 +58,8 @@ class UdpSocketTest extends TestCase
$socket->close();
}
public function testWriteAfterCloseErrors()
public function testWriteAfterCloseReopened()
{
$this->expectException(\RuntimeException::class);
$socket = new UdpSocket('127.0.0.1', 514);
$socket->close();
$socket->write('foo', "HEADER");