?php
class server
{
public $port;
public $ip;
protected $server;
public function __construct($ip = '0.0.0.0', $port)
{
$this->ip = $ip;
$this->port = $port;
$this->createSocket(); //創(chuàng)建一個通訊節(jié)點
}
public function listen($callback)
{
if(!is_callable($callback)){
throw new Exception('不是閉包,請傳遞正確的參數(shù)');
}
//只要我們接收到客戶端的數(shù)據(jù),就fork一個子進程處理
while ($client = socket_accept($this->server)) { //等待客戶端接入,返回的是客戶端的連接
$buf = socket_read($client, 1024); //讀取客戶端內(nèi)容
$pid=pcntl_fork(); //創(chuàng)建子進程
//父進程和子進程都會執(zhí)行下面代碼
if ($pid == -1) {
//錯誤處理:創(chuàng)建子進程失敗時返回-1.
die('could not fork');
} else if ($pid) {
//父進程會得到子進程號,所以這里是父進程執(zhí)行的邏輯
var_dump('父進程',$pid);
pcntl_wait($status); //等待子進程中斷,防止子進程成為僵尸進程。
} else {
//子進程得到的$pid為0, 所以這里是子進程執(zhí)行的邏輯。
//睡眠
if($this->checkRule("/sleep/i",$buf)){
sleep(10);
$this->response('休眠10S',$client);
socket_close($client);
return;
}
//請求過濾
if(empty($this->checkRule("/GET\s(.*?)\sHTTP\/1.1/i",$buf))){
socket_close($client);
return;
}
//響應
$response= call_user_func($callback,$buf); //回調(diào)$callback函數(shù)
$this->response($response,$client);
usleep(1000); //微妙為單位,1000000 微妙等于1秒
socket_close($client);
exit(); //直接退出
}
}
// while (true) {
// $client = socket_accept($this->server); //等待客戶端接入,返回的是客戶端的連接
// $buf = socket_read($client, 1024); //讀取客戶端內(nèi)容
//
// //睡眠
// if($this->checkRule("/sleep/i",$buf)){
// sleep(10);
// $this->response('休眠10S',$client);
// socket_close($client);
// return;
// }
// //請求過濾
// if(empty($this->checkRule("/GET\s(.*?)\sHTTP\/1.1/i",$buf))){
// socket_close($client);
// return;
// }
//
// //響應
// $response= call_user_func($callback,$buf); //回調(diào)$callback函數(shù)
// $this->response($response,$client);
// usleep(1000); //微妙為單位,1000000 微妙等于1秒
// socket_close($client);
//
// }
socket_close($this->server);
}
//io 復用
//epoll 模型
//多進程
protected function createSocket()
{
$this->server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//bind
socket_set_option($this->server, SOL_SOCKET, SO_REUSEADDR, 1); //復用還處于 TIME_WAIT
socket_bind($this->server, $this->ip, $this->port); //細節(jié)性的處理自行完成
socket_listen($this->server); //開始監(jiān)聽
}
/**
* 協(xié)議過濾
* @param $reg
* @param $buf
* @return mixed
*/
protected function checkRule($reg,$buf){
if(preg_match($reg,$buf,$matchs)){
return $matchs;
}
return false;
}
//請求處理類
public function request($buf){
//1.只允許http協(xié)議訪問
// if(preg_match("GET\s(.*?)\sHTTP/1.1",$buf,$matchs)){ //匹配到http協(xié)議
// return true;
// }else{
// return false;
// }
//2.過濾掉/favicon.ico
//3.獲取請求信息
}
protected function response($content,$client){
//返回數(shù)據(jù)給客戶端,響應處理
$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";
socket_write($client,$string.$content);
}
}
更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《PHP進程與線程操作技巧總結》、《PHP網(wǎng)絡編程技巧總結》、《PHP基本語法入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》