-
Notifications
You must be signed in to change notification settings - Fork 1
/
ConnectionsPool.php
66 lines (50 loc) · 2.25 KB
/
ConnectionsPool.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
<?php
require __DIR__.'/vendor/autoload.php';
use React\Socket\ConnectionInterface;
class ConnectionsPool{
protected $connections;
public function __construct()
{
$this->connections = new SplObjectStorage();
}
protected function setConnectionData(ConnectionInterface $connection, $data){
$this->connections->offsetSet($connection, $data);
}
protected function getConnectionData(ConnectionInterface $connection){
$this->connections->offsetGet($connection);
}
public function add(ConnectionInterface $connection){
$connection->write("Unesi korisničko ime: ");
$this->initEvents($connection);
$this->setConnectionData($connection, []);
$this->connections->attach($connection);
$this->sendAll("Novi korisnik je ušao u chat\n", $connection);
}
protected function initEvents(ConnectionInterface $connection){
$connection->on('data', function($data) use ($connection){
$connectionData = $this->getConnectionData($connection);
if(empty($connectionData)){
$this->sendJoinMessage($data, $connection);
return;
}
$name = $connectionData['name'];
$this->sendAll("$name: $data", $connection);
});
$connection->on('close', function() use ($connection){
$connectionData = $this->getConnectionData($connection);
$name = $connectionData['name'];
$this->connections->offsetUnset($connection);
$this->sendAll("Korisnik $name je napustio chat\n", $connection);
});
}
protected function sendJoinMessage($name, $connection){
$name = str_replace(['\n', '\r'], " ", $name);
$this->setConnectionData($connection, ['name' => $name]);
$this->sendAll("Korisnik $name je ušao u chat\n", $connection);
}
protected function sendAll($text, ConnectionInterface $connection){
foreach ($this->connections as $conn) {
if($conn !== $connection) $conn->write($text);
}
}
}