-
Notifications
You must be signed in to change notification settings - Fork 195
/
Copy pathPushClient.php
82 lines (71 loc) · 2.21 KB
/
PushClient.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
<?php
declare(strict_types=1);
namespace Bloatless\WebSocket;
class PushClient
{
/**
* Path to unix domain socket.
*
* @var string $ipcSocketPath
*/
private string $ipcSocketPath;
private const MAX_PAYLOAD_LENGTH = 65536;
public function __construct(string $ipcSocketPath = '/tmp/phpwss.sock')
{
$this->ipcSocketPath = $ipcSocketPath;
}
/**
* Push server control command.
*
* @param string $command
* @param array $data
* @return bool
*/
public function sendServerCommand(string $command, array $data): bool
{
$payload = IPCPayloadFactory::makeServerPayload($command, $data);
return $this->sendPayloadToServer($payload);
}
/**
* Pushes data into an application running within the websocket server.
*
* @param string $applicationName
* @param array $data
* @return bool
*/
public function sendToApplication(string $applicationName, array $data): bool
{
$payload = IPCPayloadFactory::makeApplicationPayload($applicationName, $data);
return $this->sendPayloadToServer($payload);
}
/**
* Pushes payload into the websocket server using a unix domain socket.
*
* @param IPCPayload $payload
* @return bool
*/
private function sendPayloadToServer(IPCPayload $payload): bool
{
$dataToSend = $payload->asJson();
$dataLength = strlen($dataToSend);
if ($dataLength > self::MAX_PAYLOAD_LENGTH) {
throw new \RuntimeException(
sprintf(
'IPC payload exceeds max length of %d bytes. (%d bytes given.)',
self::MAX_PAYLOAD_LENGTH,
$dataLength
)
);
}
$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
if ($socket === false) {
throw new \RuntimeException('Could not open ipc socket.');
}
$bytesSend = socket_sendto($socket, $dataToSend, $dataLength, MSG_EOF, $this->ipcSocketPath, 0);
if ($bytesSend <= 0) {
throw new \RuntimeException('Could not sent data to IPC socket.');
}
socket_close($socket);
return true;
}
}