Skip to content
This repository was archived by the owner on Oct 30, 2024. It is now read-only.

Commit 9e3eb23

Browse files
authored
TASK: More solid method to send payload to the socket
I can happens that fwrite does exit but without sending the full payload, or it can also happen that the pipe is closed or broken. With the change the logic a bit more complex but retry write operation. We need to silently ignore (@fwrite) notice/warnings from fwrite to be able to catch the broken pipe error (without the silent operator fwrite, will return a notice, and depending on the user php configuration, error handler, level, ... this can be converted to an exception or something that will skip the retry logic and our exception)
1 parent d1fc1da commit 9e3eb23

1 file changed

Lines changed: 15 additions & 1 deletion

File tree

src/Nats/Connection.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,21 @@ public function __construct(ConnectionOptions $options = null)
148148
private function send($payload)
149149
{
150150
$msg = $payload."\r\n";
151-
fwrite($this->streamSocket, $msg, strlen($msg));
151+
$len = strlen($msg);
152+
while (true) {
153+
if (false === ($written = @fwrite($this->streamSocket, $msg))) {
154+
throw new \Exception('Error sending data');
155+
}
156+
if ($written === 0) {
157+
throw new \Exception('Broken pipe or closed connection');
158+
}
159+
$len = $len - $written;
160+
if ($len > 0) {
161+
$msg = substr($msg, 0 - $len);
162+
} else {
163+
break;
164+
}
165+
}
152166
}
153167

154168
/**

0 commit comments

Comments
 (0)