Skip to content

Commit

Permalink
Enhancement for alive strategy.
Browse files Browse the repository at this point in the history
  • Loading branch information
lotharthesavior committed Dec 30, 2023
1 parent 79acf09 commit 6fe1d9e
Showing 1 changed file with 44 additions and 4 deletions.
48 changes: 44 additions & 4 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

namespace Kanata\ConveyorServerClient;

use co;
use Exception;
use OpenSwoole\Timer;
use Psr\Log\LoggerInterface;
use WebSocket\BadOpcodeException;
use WebSocket\Client as WsClient;
Expand Down Expand Up @@ -79,6 +81,11 @@ class Client implements ClientInterface
*/
protected int $reconnectionAttemptsCount = 0;

/**
* @var ?int Timer id for ping.
*/
protected ?int $pingTimer = null;

protected ?LoggerInterface $logger = null;

public function __construct(array $options)
Expand All @@ -95,7 +102,27 @@ public function getClient(): ?WsClient
return $this->client;
}

public function getPingTimer(): ?int
{
return $this->pingTimer;
}

/**
* @throws TimeoutException|Exception
*/
public function connect(): void
{
co::run(function () {
go(fn () => $this->startConnection());
go(fn () => $this->pingTimer = Timer::tick(5000, function () {
if ($this->getClient() && $this->getClient()->isConnected()) {
$this->getClient()->ping();
}
}));
});
}

private function startConnection()
{
try {
$this->handleClientConnection();
Expand Down Expand Up @@ -155,6 +182,9 @@ protected function handleDisconnection(): void
);
}

/**
* @throws TimeoutException|Exception
*/
protected function handleClientConnection(): void
{
$this->client = new WsClient(
Expand All @@ -170,11 +200,20 @@ protected function handleClientConnection(): void
$this->handleListeners();
$this->connectionReady();

while($message = $this->client->receive()) {
if (null === $this->onMessageCallback) {
continue;
try {
while ($message = $this->client->receive()) {
if (null === $this->onMessageCallback) {
continue;
}
call_user_func($this->onMessageCallback, $this, $message);
}
call_user_func($this->onMessageCallback, $this, $message);
} catch (TimeoutException $e) {
if ($this->timeout === -1) {
throw $e;
}
$this->close();
} catch (Exception $e) {
throw $e;
}
}

Expand Down Expand Up @@ -215,6 +254,7 @@ protected function connectionReady(): void

public function close(): void
{
Timer::clear($this->getPingTimer());
$this->client->close();
$this->client = null;
}
Expand Down

0 comments on commit 6fe1d9e

Please sign in to comment.