forked from amal/AzaLibEvent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffered_api.php
77 lines (61 loc) · 1.75 KB
/
buffered_api.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
<?php
use Aza\Components\LibEvent\EventBase;
use Aza\Components\LibEvent\EventBuffer;
require __DIR__ . '/../vendor/autoload.php';
/**
* Example #2 - polling STDIN using buffered event API
*
* @link http://www.php.net/manual/en/libevent.examples.php
*
* @project Anizoptera CMF
* @package system.libevent
* @author Amal Samally <amal.samally at gmail.com>
* @license MIT
*/
/**
* Callback to invoke where there is data to read
*
* @param resource $buf File descriptor
* @param array $args Event arguments - array(EventBuffer $e, mixed $arg)
*/
function print_line($buf, $args)
{
static $max_requests;
$max_requests++;
/**
* @var $e EventBuffer
* @var $base EventBase
*/
list($e, $base) = $args;
// exit loop after 10 writes
if ($max_requests == 10) {
$base->loopExit();
}
// print the line
echo $e->read(4096);
}
/**
* Callback to invoke where there is an error on the descriptor.
* function(resource $buf, int $what, array $args(EventBuffer $e, mixed $arg))
*
* @param resource $buf File descriptor
* @param int $what What kind of error occurred. See EventBuffer::E_* constants
* @param array $args Event arguments - array(EventBuffer $e, mixed $arg)
*/
function error_func($buf, $what, $args) {}
// I use EventBase::getMainLoop() here to operate always with the
// same instance, but you can simply use "new EventBase()"
// Get event base
$loop = EventBase::getMainLoop();
// Create buffered event
$ev = new EventBuffer(STDIN, 'print_line', null, 'error_func', $loop);
$ev->setBase($loop)->enable(EV_READ);
// Start event loop once
$loop->loop(EVLOOP_NONBLOCK);
// Fork support test
//if (!$pid = $loop->fork()) {
// exit; // exit in child
//}
//pcntl_waitpid($pid, $status, WUNTRACED);
// Start event loop
$loop->loop();