//連接重用
//創(chuàng)建資源流的上下文
$context=stream_context_create([
'socket'=>[
'backlog'=>2000
]]);
stream_context_set_option($context,'socket','so_reuseaddr',1); //設(shè)置連接重用
//sock_set_option($this->server, SOL_SOCKET, SO_REUSEADDR, 1); //復(fù)用還處于 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();
//監(jiān)聽服務(wù)端的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();
//監(jiān)聽客戶端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);
//當(dāng)socket斷開連接,刪除事件
$event->del();//刪除事件
});
$event->add(); //加入事件監(jiān)聽
$base->loop();
//監(jiān)視客戶端
//$event->del();//刪除事件
});
$event->add(); //加入事件監(jiān)聽
var_dump($base->loop()); //調(diào)度掛起事件監(jiān)聽
以上就是php使用event擴(kuò)展的io復(fù)用測試的示例的詳細(xì)內(nèi)容,更多關(guān)于php io復(fù)用測試的資料請關(guān)注腳本之家其它相關(guān)文章!