标签:
libevent是一个基于事件驱动的高性能网络库。支持多种 I/O 多路复用技术, epoll、 poll、 dev/poll、 select 和 kqueue 等;支持 I/O,定时器和信号等事件;注册事件优先级。
PHP libevent扩展安装:
libevent扩展依赖于原始的libevent库,必须先把libevent库安装。
(1)安装libevent库
wget http://cloud.github.com/downloads/libevent/libevent/libevent-2.0.20-stable.tar.gz tar zxvf libevent-2.0.20-stable.tar.gz cd libevent-2.0.20-stable/ ./configure --prefix=/usr/local/libevent-2.0.20/ make make install
(2)安装libevent扩展(http://pecl.php.net/package/libevent)wget http://pecl.php.net/get/libevent-0.1.0.tgz
tar -zxvf libevent-0.1.0.tgz cd libevent-0.1.0
#使用phpize生成configure文件
phpize
./configure --with-php-config=/usr/local/php54/bin/php-config --with-libevent=/usr/local/libevent-2.0.20/ make && make install #php.ini添加extension=libevent.so
PHP Libevent扩展使用:
例1:5s后触发callback
$base = event_base_new(); $event = event_new(); event_set($event, 0, EV_TIMEOUT, function() { echo "function called"; }); event_base_set($event, $base); event_add($event, 5000000); event_base_loop($base);
例2:打印输入流
function print_line($fd, $events, $arg) { static $max_requests = 0; $max_requests++; if ($max_requests == 10) { // exit loop after 10 writes event_base_loopexit($arg[1]); } echo fgets($fd); } // create base and event $base = event_base_new(); $event = event_new(); $fd = STDIN; // set event flags event_set($event, $fd, EV_READ | EV_PERSIST, ‘print_line‘, array($event, $base)); // set event base event_base_set($event, $base); // enable event event_add($event); // start event loop event_base_loop($base);
例3:实现简单web server
在cli执行后,打开浏览器2000端口试试看。
$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) { while ($read = event_buffer_read($buffer, 256)) { } fwrite($connection , date(‘Y-m-d H:i:s‘)); ev_error($buffer , ‘‘ , $connection); }
参考资料:
原文:
http://www.phpddt.com/php/libevent.html
标签:
原文地址:http://www.cnblogs.com/chunguang/p/5555865.html