-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSocketTransport.php
More file actions
61 lines (53 loc) · 1.56 KB
/
WebSocketTransport.php
File metadata and controls
61 lines (53 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
declare(strict_types=1);
namespace Arcp\Transport;
use Amp\Cancellation;
use Amp\Websocket\WebsocketClient;
use Arcp\Envelope\Envelope;
use Arcp\Json\EnvelopeSerializer;
/**
* RFC §22 mandatory WebSocket transport. Wraps an Amp v3
* {@see WebsocketClient} (server-side or client-side) and routes each
* envelope through a single text frame containing the JSON-encoded body.
*
* Sidecar binary frames are deferred to v0.2; v0.1 advertises only
* `binary_encoding: ["base64"]`, so binary streams travel inline.
*/
final class WebSocketTransport implements Transport
{
public function __construct(
private readonly WebsocketClient $ws,
private readonly EnvelopeSerializer $serializer,
) {
}
#[\Override]
public function send(Envelope $env, ?Cancellation $cancellation = null): void
{
if ($this->ws->isClosed()) {
throw new \RuntimeException('websocket closed');
}
$this->ws->sendText($this->serializer->encode($env));
}
#[\Override]
public function receive(?Cancellation $cancellation = null): ?Envelope
{
$message = $this->ws->receive($cancellation);
if ($message === null) {
return null;
}
$payload = $message->buffer($cancellation);
return $this->serializer->decode($payload);
}
#[\Override]
public function close(): void
{
if (!$this->ws->isClosed()) {
$this->ws->close();
}
}
#[\Override]
public function isClosed(): bool
{
return $this->ws->isClosed();
}
}