Skip to content

Commit

Permalink
Allow UdpSocket to reconnect after close()
Browse files Browse the repository at this point in the history
  • Loading branch information
Seldaek committed May 10, 2022
1 parent c709906 commit 5d43fd5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 16 deletions.
40 changes: 27 additions & 13 deletions src/Monolog/Handler/SyslogUdp/UdpSocket.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand All @@ -57,12 +49,34 @@ public function close(): void
}
}

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
Expand Down
4 changes: 1 addition & 3 deletions tests/Monolog/Handler/UdpSocketTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,8 @@ public function testDoubleCloseDoesNotError()
$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");
Expand Down

0 comments on commit 5d43fd5

Please sign in to comment.