forked from igorw/webserver-zceu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path99-event-loop.php
92 lines (78 loc) · 2.09 KB
/
99-event-loop.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
<?php
class EventLoop
{
public $read = [], $write = [];
public $onReadable = [], $onWritable = [];
function run()
{
while (true) {
$this->tick();
}
}
function tick()
{
$readable = $this->read ?: null;
$writable = $this->write ?: null;
$except = null;
if (stream_select($readable, $writable, $except, 1)) {
$readable = $readable ?: [];
foreach ($readable as $stream) {
$this->callReadListener($stream);
}
$writable = $writable ?: [];
foreach ($writable as $stream) {
$this->callWriteListener($stream);
}
}
}
function onReadable($stream, callable $listener)
{
$this->onReadable[(int) $stream] = $listener;
$this->enableReads($stream);
}
function onWritable($stream, callable $listener)
{
$this->onWritable[(int) $stream] = $listener;
}
function enableReads($stream)
{
$this->read[] = $stream;
}
function disableReads($stream)
{
if (false !== $index = array_search($stream, $this->read)) {
array_splice($this->read, $index);
}
}
function enableWrites($stream)
{
$this->write[] = $stream;
}
function disableWrites($stream)
{
if (false !== $index = array_search($stream, $this->write)) {
array_splice($this->write, $index);
}
}
function callReadListener($stream)
{
if (isset($this->onReadable[(int) $stream])) {
$listener = $this->onReadable[(int) $stream];
$listener($stream);
}
}
function callWriteListener($stream)
{
if (isset($this->onWritable[(int) $stream])) {
$listener = $this->onWritable[(int) $stream];
$listener($stream);
}
}
function remove($stream)
{
$this->disableReads($stream);
$this->disableWrites($stream);
unset($this->onReadable[(int) $stream]);
unset($this->onWritable[(int) $stream]);
}
}