This repository has been archived by the owner on Feb 7, 2024. It is now read-only.
/
WebSocketHandler.php
93 lines (74 loc) · 2.83 KB
/
WebSocketHandler.php
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
namespace BeyondCode\LaravelWebSockets\WebSockets;
use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger;
use BeyondCode\LaravelWebSockets\Events\ConnectionEstablished;
use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\WebSocketException;
use BeyondCode\LaravelWebSockets\WebSockets\Messages\RespondableMessageFactory;
use BeyondCode\LaravelWebSockets\QueryParameters;
use Exception;
use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface;
use BeyondCode\LaravelWebSockets\ClientProviders\Client;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\UnknownAppKey;
use Ratchet\WebSocket\MessageComponentInterface;
class WebSocketHandler implements MessageComponentInterface
{
/** @var \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager */
protected $channelManager;
public function __construct(ChannelManager $channelManager)
{
$this->channelManager = $channelManager;
}
function onOpen(ConnectionInterface $connection)
{
$this
->generateSocketId($connection)
->verifyConnection($connection)
->establishConnection($connection);
}
public function onMessage(ConnectionInterface $connection, MessageInterface $message)
{
$message = RespondableMessageFactory::createForMessage($message, $connection, $this->channelManager);
$message->respond();
}
public function onClose(ConnectionInterface $connection)
{
$this->channelManager->removeFromAllChannels($connection);
}
public function onError(ConnectionInterface $connection, Exception $exception)
{
if ($exception instanceof WebSocketException) {
$connection->send(json_encode(
$exception->getPayload()
));
}
}
protected function generateSocketId(ConnectionInterface $connection)
{
$socketId = sprintf("%d.%d", random_int(1, 1000000000), random_int(1, 1000000000));
$connection->socketId = $socketId;
return $this;
}
protected function verifyConnection(ConnectionInterface $connection)
{
$appKey = QueryParameters::create($connection->httpRequest)->get('appKey');
if (!$client = Client::findByAppKey($appKey)) {
throw new UnknownAppKey($appKey);
}
$connection->client = $client;
return $this;
}
protected function establishConnection(ConnectionInterface $connection)
{
$connection->send(json_encode([
'event' => 'pusher:connection_established',
'data' => json_encode([
'socket_id' => $connection->socketId,
'activity_timeout' => 30,
])
]));
DashboardLogger::connection($connection);
return $this;
}
}