/usr/local/php/bin/pecl install channel://pecl.php.net/libevent-0.0.4
添加 extension=libevent.so 到 php.ini
基于libevent的简单server 监听2000端口 打印回当前时间
<?php
$socket = stream_socket_server ('tcp://0.0.0.0:2000', $errno, $errstr);
stream_set_blocking($socket, 0);
$base = event_base_new();
$event = event_new();
event_set($event, $socket, EV_READ | EV_PERSIST, 'ev_accept', $base);
event_base_set($event, $base);
event_add($event);
event_base_loop($base);
function ev_accept($socket, $flag, $base) {
$connection = stream_socket_accept($socket);
stream_set_blocking($connection, 0);
$buffer = event_buffer_new($connection, 'ev_read', NULL, 'ev_error', $connection);
event_buffer_base_set($buffer, $base);
event_buffer_timeout_set($buffer, 30, 30);
event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff);
event_buffer_priority_set($buffer, 10);
event_buffer_enable($buffer, EV_READ | EV_PERSIST);
$GLOBALS['_'] = $buffer; /
/这个buffer一定要赋给个全局的变量 貌似是传值过程中的bug 或者5.3.8的闭包还是有问题?
}
function ev_error($buffer, $error, $connection) {
event_buffer_disable($buffer, EV_READ | EV_WRITE);
event_buffer_free($buffer);
fclose($connection);
}
function ev_read($buffer, $connection) {
// var_dump($connection);
while ($read = event_buffer_read($buffer, 256)) {
// var_dump($read);
}
fwrite($connection , date('Y-m-d H:i:s'));
ev_error($buffer , '' , $connection);
}
?>
通过浏览器访问下这台机器的2000端口 yeah~