Skip to content

Commit f40de82

Browse files
committed
Fix onClose handler on socket disconnect
1 parent 227e285 commit f40de82

2 files changed

Lines changed: 16 additions & 5 deletions

File tree

src/Internal/Rfc6455FrameHandler.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Amp\DeferredFuture;
88
use Amp\ForbidCloning;
99
use Amp\ForbidSerialization;
10+
use Amp\Future;
1011
use Amp\Pipeline\ConcurrentIterator;
1112
use Amp\Pipeline\DisposedException;
1213
use Amp\Pipeline\Queue;
@@ -299,6 +300,20 @@ public function close(int $code, string $reason = '', bool $byPeer = false): voi
299300
$this->socket->close();
300301
}
301302

303+
/**
304+
* @param \Closure(int, WebsocketCloseInfo):void $onClose
305+
*/
306+
public function onClose(\Closure $onClose): void
307+
{
308+
$future = $this->closeDeferred?->getFuture() ?? Future::complete();
309+
310+
$metadata = $this->metadata;
311+
$future->finally(static function () use ($onClose, $metadata): void {
312+
\assert($metadata->closeInfo !== null, 'Client was not closed when onClose invoked');
313+
$onClose($metadata->id, $metadata->closeInfo);
314+
});
315+
}
316+
302317
private static function createMessage(WebsocketFrameType $frameType, ReadableStream|string $stream): WebsocketMessage
303318
{
304319
if ($frameType === WebsocketFrameType::Binary) {

src/Rfc6455Client.php

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -307,10 +307,6 @@ public function close(int $code = WebsocketCloseCode::NORMAL_CLOSE, string $reas
307307

308308
public function onClose(\Closure $onClose): void
309309
{
310-
$metadata = $this->metadata;
311-
$this->socket->onClose(static function () use ($onClose, $metadata): void {
312-
\assert($metadata->closeInfo !== null, 'Client was not closed when onClose invoked');
313-
$onClose($metadata->id, $metadata->closeInfo);
314-
});
310+
$this->frameHandler->onClose($onClose);
315311
}
316312
}

0 commit comments

Comments
 (0)