-
Notifications
You must be signed in to change notification settings - Fork 0
/
3-http-io-non-blocking.php
40 lines (31 loc) · 1.06 KB
/
3-http-io-non-blocking.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
<?php
$streamList = [
stream_socket_client('tcp://localhost:8080'),
fopen('2-file1.txt', 'r'),
fopen('2-file2.txt', 'r')
];
fwrite($streamList[0], 'GET /http-server.php HTTP/1.1' . PHP_EOL . PHP_EOL);
foreach ($streamList as $stream) {
stream_set_blocking($stream, false);
}
do {
$copyReadStream = $streamList;
$numberOfChangedStreams = stream_select($copyReadStream, $write, $except, 0, 0);
// To avoid CPU high usage
if ($numberOfChangedStreams === 0) {
// echo 'Do some async tasks here =)' . PHP_EOL;
continue;
}
foreach ($copyReadStream as $key => $stream) {
$content = stream_get_contents($stream);
// Jump HTTP headers, if is a HTTP stream
$endHTTPHeadersPosition = strpos($content, "\r\n\r\n");
if ($endHTTPHeadersPosition !== false) {
echo substr($content, $endHTTPHeadersPosition + 4); // 4 = \r\n\r\n
} else {
echo $content;
}
unset($streamList[$key]);
}
} while (!empty($streamList));
echo 'Read All Streams =)' . PHP_EOL;