forked from igorw/webserver-zceu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-event-loop.php
42 lines (35 loc) · 1.1 KB
/
03-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
<?php
$server = stream_socket_server('tcp://0.0.0.0:5000');
$read = [$server];
$write = [];
while (true) {
$readable = $read ?: null;
$writable = $write ?: null;
$except = null;
if (stream_select($readable, $writable, $except, 1)) {
$readable = $readable ?: [];
foreach ($readable as $stream) {
if ($server === $stream) {
$conn = stream_socket_accept($server, 0);
$read[] = $conn;
} else {
$data = fread($stream, 1024);
if (!$data) {
if (false !== $index = array_search($stream, $read)) {
array_splice($read, $index);
}
if (false !== $index = array_search($stream, $write)) {
array_splice($write, $index);
}
fclose($stream);
continue;
}
echo "[$stream] $data";
}
}
$writable = $writable ?: [];
foreach ($writable as $stream) {
// ...
}
}
}