Skip to content

Commit

Permalink
Fix onClose handler on socket disconnect
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed Sep 14, 2023
1 parent 227e285 commit f40de82
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
15 changes: 15 additions & 0 deletions src/Internal/Rfc6455FrameHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Amp\DeferredFuture;
use Amp\ForbidCloning;
use Amp\ForbidSerialization;
use Amp\Future;
use Amp\Pipeline\ConcurrentIterator;
use Amp\Pipeline\DisposedException;
use Amp\Pipeline\Queue;
Expand Down Expand Up @@ -299,6 +300,20 @@ public function close(int $code, string $reason = '', bool $byPeer = false): voi
$this->socket->close();
}

/**
* @param \Closure(int, WebsocketCloseInfo):void $onClose
*/
public function onClose(\Closure $onClose): void
{
$future = $this->closeDeferred?->getFuture() ?? Future::complete();

$metadata = $this->metadata;
$future->finally(static function () use ($onClose, $metadata): void {
\assert($metadata->closeInfo !== null, 'Client was not closed when onClose invoked');
$onClose($metadata->id, $metadata->closeInfo);
});
}

private static function createMessage(WebsocketFrameType $frameType, ReadableStream|string $stream): WebsocketMessage
{
if ($frameType === WebsocketFrameType::Binary) {
Expand Down
6 changes: 1 addition & 5 deletions src/Rfc6455Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -307,10 +307,6 @@ public function close(int $code = WebsocketCloseCode::NORMAL_CLOSE, string $reas

public function onClose(\Closure $onClose): void
{
$metadata = $this->metadata;
$this->socket->onClose(static function () use ($onClose, $metadata): void {
\assert($metadata->closeInfo !== null, 'Client was not closed when onClose invoked');
$onClose($metadata->id, $metadata->closeInfo);
});
$this->frameHandler->onClose($onClose);
}
}

1 comment on commit f40de82

@bennnjamin
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just encountered this when a client is forcefully terminated, thanks for the fix! 👍

Please sign in to comment.