码迷,mamicode.com
首页 > Web开发 > 详细

[PHP] php使用event扩展的io复用测试

时间:2019-12-13 19:58:41      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:char   world   com   use   var   str   bind   soc   add   

先要安装event扩展,这样才可以使用libevent的事件机制

pecl install event

测试代码

//连接重用
//创建资源流的上下文
$context=stream_context_create([
    ‘socket‘=>[
        ‘backlog‘=>2000
    ]]);
stream_context_set_option($context,‘socket‘,‘so_reuseaddr‘,1); //设置连接重用
//sock_set_option($this->server, SOL_SOCKET, SO_REUSEADDR, 1); //复用还处于 TIME_WAIT
$socket = stream_socket_server("tcp://0.0.0.0:8070", $errno, $errstr,STREAM_SERVER_BIND | STREAM_SERVER_LISTEN,$context);
stream_set_blocking($socket,false);//非阻塞
//绑定事件
$base=new EventBase();
//监听服务端的socket
$event=new  Event($base,$socket,Event::PERSIST |Event::READ | Event::WRITE,function ($socket)use(&$base){

    $client = stream_socket_accept($socket);
    //stream_set_blocking($client,false);//非阻塞
//        var_dump($client);
//        $content=‘21335435‘;
//        $string="HTTP/1.1 200 OK\r\n";
//        $string.="Content-Type: text/html;charset=utf-8\r\n";
//        $string.="Content-Length: ".strlen($content)."\r\n\r\n";
//        fwrite($client,$string.$content);
//        fclose($client);

    //global $base;

    //var_dump($socket,$client);

    $base=new EventBase();
    //监听客户端socket
    $event=new  Event($base,$client,Event::PERSIST |Event::READ | Event::WRITE,function ($client){
        $msg=fread($client,65535);
//
//         if($msg){ //匹配请求头包含了keep-alive
//
//         }

        $content=‘hello world‘;
        $string="HTTP/1.1 200 OK\r\n";
        $string.="Content-Type: text/html;charset=utf-8\r\n";
        $string.="Connection: keep-alive\r\n";
        $string.="Content-Length: ".strlen($content)."\r\n\r\n";
        fwrite($client,$string.$content);

        fclose($client);

 
        //当socket断开连接,删除事件

        $event->del();//删除事件


    });
    $event->add(); //加入事件监听
    $base->loop();

    //监视客户端
    //$event->del();//删除事件
});
$event->add(); //加入事件监听
var_dump($base->loop()); //调度挂起事件监听

技术图片

 

 

技术图片

 

[PHP] php使用event扩展的io复用测试

标签:char   world   com   use   var   str   bind   soc   add   

原文地址:https://www.cnblogs.com/taoshihan/p/12036811.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!