forked from bloatless/php-websocket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chat.php
105 lines (92 loc) · 2.56 KB
/
Chat.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
94
95
96
97
98
99
100
101
102
103
104
105
<?php
declare(strict_types=1);
namespace Bloatless\WebSocketExamples\Application;
use Bloatless\WebSocket\Application\Application;
use Bloatless\WebSocket\Connection;
class Chat extends Application
{
/**
* @var array $clients
*/
private array $clients = [];
/**
* @var array $nicknames
*/
private array $nicknames = [];
/**
* Handles new connections to the application.
*
* @param Connection $connection
* @return void
*/
public function onConnect(Connection $connection): void
{
$id = $connection->getClientId();
$this->clients[$id] = $connection;
$this->nicknames[$id] = 'Guest' . rand(10, 999);
}
/**
* Handles client disconnects.
*
* @param Connection $connection
* @return void
*/
public function onDisconnect(Connection $connection): void
{
$id = $connection->getClientId();
unset($this->clients[$id], $this->nicknames[$id]);
}
/**
* Handles incomming data/requests.
* If valid action is given the according method will be called.
*
* @param string $data
* @param Connection $client
* @return void
*/
public function onData(string $data, Connection $client): void
{
try {
$decodedData = $this->decodeData($data);
// check if action is valid
if ($decodedData['action'] !== 'echo') {
return;
}
$message = $decodedData['data'] ?? '';
if ($message === '') {
return;
}
$clientId = $client->getClientId();
$message = $this->nicknames[$clientId] . ': ' . $message;
$this->actionEcho($message);
} catch (\RuntimeException $e) {
// @todo Handle/Log error
}
}
/**
* Handles data pushed into the websocket server using the push-client.
*
* @param array $data
*/
public function onIPCData(array $data): void
{
$actionName = 'action' . ucfirst($data['action']);
$message = 'System Message: ' . $data['data'] ?? '';
if (method_exists($this, $actionName)) {
call_user_func([$this, $actionName], $message);
}
}
/**
* Echoes data back to client(s).
*
* @param string $text
* @return void
*/
private function actionEcho(string $text): void
{
$encodedData = $this->encodeData('echo', $text);
foreach ($this->clients as $sendto) {
$sendto->send($encodedData);
}
}
}