php使用event扩展的io复用测试的示例
先要安装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()); //调度挂起事件监听
相关推荐
一叶梧桐 2020-10-14
lzzyok 2020-10-10
digwtx 2020-09-14
efeve 2020-09-14
poplpsure 2020-08-17
ITxiaobaibai 2020-07-26
libowenhit 2020-07-23
luckykapok 2020-07-06
hongsheyoumo 2020-06-27
jannal 2020-06-21
lanmantech 2020-06-16
咻咻ing 2020-06-16
weibingbingnet 2020-06-14
woyanyouxin 2020-06-04
houjinkai 2020-06-03
txj 2020-06-02
Chydar 2020-05-15
小木兮子 2020-05-14