php 구현 간단 한 다 중 프로 세 스 서버 클래스 전체 예시
4276 단어 php다 중 프로 세 스서버 클래스
php 가 작성 한 간단 한 다 중 프로 세 스 서버
<?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(); //
}
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
";
$string.="Content-Type: text/html;charset=utf-8\r
";
$string.="Content-Length: ".strlen($content)."\r
\r
";
socket_write($client,$string.$content);
}
}
더 많은 PHP 관련 내용 에 관심 이 있 는 독자 들 은 본 사이트 의 주 제 를 볼 수 있다.본 논문 에서 말 한 것 이 여러분 의 PHP 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Laravel - 변환된 유효성 검사 규칙으로 API 요청 제공동적 콘텐츠를 위해 API를 통해 Laravel CMS에 연결하는 모바일 앱(또는 웹사이트) 구축을 고려하십시오. 이제 앱은 CMS에서 번역된 콘텐츠를 받을 것으로 예상되는 다국어 앱이 될 수 있습니다. 일반적으로 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.