This repository has been archived by the owner on Sep 19, 2018. It is now read-only.
/
Server.php
64 lines (51 loc) · 1.41 KB
/
Server.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
<?php
/* (c) Anton Medvedev <anton@elfet.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Elfet\Chat;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Server implements MessageComponentInterface
{
private $clients;
private $messages = [];
public function __construct()
{
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn)
{
$user = $conn->Session->get('user');
$conn->user = $user;
$this->clients->attach($conn);
$conn->send(json_encode($this->messages));
}
public function onMessage(ConnectionInterface $from, $message)
{
$message = trim($message);
if (empty($message)) {
return;
}
$message = [
'text' => $message,
'user' => $from->user,
];
$this->messages[] = $message;
foreach ($this->clients as $client) {
$client->send(json_encode([$message]));
}
if(count($this->messages) > 10) {
array_shift($this->messages);
}
}
public function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
$conn->close();
}
}