本文實例講述了php實現的簡單多進程服務器類。分享給大家供大家參考,具體如下:
php寫的一個簡單的多進程服務器。
<?phpclass server{ public $port; public $ip; protected $server; public function __construct($ip = '0.0.0.0', $port) { $this->ip = $ip; $this->port = $port; $this->createSocket(); //創建一個通訊節點 } public function listen($callback) { if(!is_callable($callback)){ throw new Exception('不是閉包,請傳遞正確的參數'); } //只要我們接收到客戶端的數據,就fork一個子進程處理 while ($client = socket_accept($this->server)) { //等待客戶端接入,返回的是客戶端的連接 $buf = socket_read($client, 1024); //讀取客戶端內容 $pid=pcntl_fork(); //創建子進程 //父進程和子進程都會執行下面代碼 if ($pid == -1) { //錯誤處理:創建子進程失敗時返回-1. die('could not fork'); } else if ($pid) { //父進程會得到子進程號,所以這里是父進程執行的邏輯 var_dump('父進程',$pid); pcntl_wait($status); //等待子進程中斷,防止子進程成為僵尸進程。 } else { //子進程得到的$pid為0, 所以這里是子進程執行的邏輯。 //睡眠 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); //回調$callback函數 $this->response($response,$client); usleep(1000); //微妙為單位,1000000 微妙等于1秒 socket_close($client); exit(); //直接退出 } }// while (true) {// $client = socket_accept($this->server); //等待客戶端接入,返回的是客戶端的連接// $buf = socket_read($client, 1024); //讀取客戶端內容//// //睡眠// 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); //回調$callback函數// $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); //細節性的處理自行完成 socket_listen($this->server); //開始監聽 } /** * 協議過濾 * @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協議訪問// if(preg_match("GET/s(.*?)/sHTTP/1.1",$buf,$matchs)){ //匹配到http協議// return true;// }else{// return false;// } //2.過濾掉/favicon.ico //3.獲取請求信息 } protected function response($content,$client){ //返回數據給客戶端,響應處理 $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); }}
新聞熱點
疑難解答