PHP使用libevent实现高性能httpServer

今天发现php也有一个libevent的扩展,安装后尝试下了一个webserver(httpserver), 发现性能还不错,逻辑很简单,每秒响应速度1800~4000次/s

代码如下

<?php
$socket = stream_socket_server ('tcp://0.0.0.0:8888', $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) {
    static $i; 
    $connection = stream_socket_accept($socket); //和客户端建立连接
    stream_set_blocking($connection, 0);
   
    $buffer = event_buffer_new($connection, 'ev_read', NULL, 'ev_error',  $connection);  // 为这个连接添加I/O缓冲事件
    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);
    echo $i++;
    echo "\n";
    $GLOBALS['b'] = $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);
}

只是简单的传输一个事件数据,没有遵守http协议, 貌似不太稳定,用浏览器反应会比较慢,期待进步一改进。

posted on 2013-10-31 20:18  出发的兰彻  阅读(997)  评论(0编辑  收藏  举报

导航