Skip to content

Commit

Permalink
Avoid the server shutdown by throwing exceptions.
Browse files Browse the repository at this point in the history
  • Loading branch information
limingxinleo committed Sep 30, 2023
1 parent fa48cab commit 1b5e32e
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions src/SafeSocket.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@
use Hyperf\Engine\Contract\SocketInterface;
use Hyperf\Engine\Exception\SocketClosedException;
use Hyperf\Engine\Exception\SocketTimeoutException;
use Psr\Log\LoggerInterface;
use Swoole\Coroutine\Socket;
use Throwable;

class SafeSocket implements SocketInterface
{
protected Channel $channel;

protected bool $loop = false;

protected ?LoggerInterface $logger = null;

public function __construct(protected Socket $socket, int $capacity = 65535, protected bool $throw = true)
{
$this->channel = new Channel($capacity);
Expand Down Expand Up @@ -93,6 +97,12 @@ public function close(): bool
return $this->socket->close();
}

public function setLogger(?LoggerInterface $logger): static
{
$this->logger = $logger;
return $this;
}

protected function loop(): void
{
if ($this->loop) {
Expand All @@ -102,15 +112,19 @@ protected function loop(): void
$this->loop = true;

Coroutine::create(function () {
while (true) {
$data = $this->channel->pop(-1);
if ($this->channel->isClosing()) {
return;
}
try {
while (true) {
$data = $this->channel->pop(-1);
if ($this->channel->isClosing()) {
return;
}

[$data, $timeout] = $data;
[$data, $timeout] = $data;

$this->socket->sendAll($data, $timeout);
$this->socket->sendAll($data, $timeout);
}
} catch (Throwable $exception) {
$this->logger?->critical((string) $exception);
}
});
}
Expand Down

0 comments on commit 1b5e32e

Please sign in to comment.