From 8624d196b1f2fd6fe643621505c44c8c156000b8 Mon Sep 17 00:00:00 2001 From: Deeka Wong <8337659+huangdijia@users.noreply.github.com> Date: Wed, 28 Aug 2024 09:40:13 +0800 Subject: [PATCH] feat: Retry connection in StreamSocketTransporter.php Retry the connection in the `StreamSocketTransporter.php` file when establishing a stream socket client. This change improves the reliability of the connection by attempting to connect multiple times before throwing a connection exception. Co-authored-by: Deeka Wong <8337659+huangdijia@users.noreply.github.com> --- src/Transporter/StreamSocketTransporter.php | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/Transporter/StreamSocketTransporter.php b/src/Transporter/StreamSocketTransporter.php index 0e32651..76e98af 100644 --- a/src/Transporter/StreamSocketTransporter.php +++ b/src/Transporter/StreamSocketTransporter.php @@ -131,21 +131,24 @@ protected function connect() if ($this->isConnected) { return; } + if ($this->client) { fclose($this->client); unset($this->client); } - [$host, $port] = $this->getTarget(); + retry(5, function() { + [$host, $port] = $this->getTarget(); - $client = stream_socket_client("tcp://{$host}:{$port}", $errno, $errstr, $this->timeout); + $client = stream_socket_client("tcp://{$host}:{$port}", $errno, $errstr, $this->timeout); - if ($client === false) { - throw new ConnectionException(sprintf('[%d] %s', $errno, $errstr)); - } + if ($client === false) { + throw new ConnectionException(sprintf('[%d] %s', $errno, $errstr)); + } - $this->client = $client; - $this->isConnected = true; + $this->client = $client; + $this->isConnected = true; + }); } protected function close()