pthreads 확장이 필요합니다 실행하려면 PHP 명령줄 모드
급하게 작성해서 최적화할 시간이 없습니다. 시간이 나면 최적화하겠습니다
来自源地址: http://www.haowei.me/archives/1009.html
- ini_set('display_errors', false);
- error_reporting(0);
- if(!class_exists( 'thread')) {
- logs('PHP 런타임 환경은 멀티 스레드를 지원하지 않습니다.');
- exit(0);
- }
- if(!function_exists('mime_content_type')) {
- 로그('PHP 런타임 환경은 mime_content_type() 함수를 지원하지 않습니다.');
- exit(0);
- }
- class pthread 확장 스레드 {
-
- protected $ 소켓 = null;
- protected $arguments = null;
- protected $connections = 0;
- protected $octet_stream = false;
-
- 공용 함수 __construct($socket, $arguments = array() ) {
-
- $this->socket = $socket;
- $this->arguments = $arguments;
- if(!isset($this->arguments['ServerTokens'] ))
- $this->arguments['ServerTokens'] = 'off';
-
-
- }
-
- 공용 함수 run() {
-
- date_default_timezone_set ('UTC');
-
- $clients = 1;
- $maxRequests = !isset($this->arguments['MaxRequests'])?
- intval($this->arguments ['MaxRequests']):
- 100;
- $timeout = 5;
-
- $connfd =socket_accept($this->socket);
- socket_set_option($connfd, SOL_SOCKET, SO_RCVTIMEO , array('초' => $timeout, 'usec' => 0));
-
- $session = 1;
-
- while($session) {
-
- $buffer = '';
- while (( $buffer .= 소켓_read ($connfd, 1024, PHP_BINARY_READ) ))
- if(strpos($buffer, "rnrn") !== false) break;
-
- if($buffer == '') {
- 소켓_close($connfd);
- $session = 0;
- }else{
-
- $availableRequests = $maxRequests - $clients;
- $clients ;
-
- $i = 0;
- $headers = array();
- array_push($headers, 'HTTP/1.1 200 OK');
- array_push($headers, '날짜: '.gmtdate());
- array_push($headers, '서버: PHP-CLI/1.0');
- array_push($headers, 'Content-Type: text/html; charset=utf-8');
- array_push($headers, ' 연결: 닫음');
-
- if($this->arguments['ServerTokens'] == 'on')
- $headers[2] = '서버: PHP-CLI';
-
- $buffer = 폭발("rn", $buffer);
-
- $http_user_agent = '';
- $http_request_method = '';
- $http_request_file = '';
- $http_protocol = '';
- $extension = '';
- $mime_types = '';
- $this->octet_stream = false;
-
- foreach($buffer as $line) {
- $pattern = '/(GET|POST)s/(.*)s(HTTP/1.[0-1])$/';
- if(preg_match($pattern, $line)) {
- $http_request_method = preg_replace($pattern, '\1', $line);
- $http_request_file = preg_replace($pattern, '\2', $line);
- $http_protocol = preg_replace($ 패턴, '\3', $line);
- }
- $pattern = '/^User-Agent: (. )$/';
- if(preg_match($pattern, $line)) {
- $http_user_agent = preg_replace($pattern, '\1', $line);
- }
- }
-
- $local_request_file = $this->인수['DocumentRoot'].'/'. $http_request_file;
- if(file_exists($local_request_file) && is_file($local_request_file))
- $extension = pathinfo($local_request_file, PATHINFO_EXTENSION);
-
- if(file_exists($local_request_file)) {
- $array_key_exists = array_key_exists($extension, $this->arguments['MimeTypes']);
-
- if(is_file($local_request_file)) {
- if($array_key_exists) {
- $mime_types = $this->arguments['MimeTypes'][$extension];
- $headers[3] = sprintf('Content-Type: %s; charset=%s', $mime_types, 'utf- 8');
- }else{
- $this->octet_stream = true;
- $headers[3] = sprintf('Content-Type: application/octet-stream');
- array_push ($headers, 'Accept-Ranges: bytes');
- array_push($headers, 'Accept-Length: '.filesize($local_request_file));
- array_push($headers, 'Content-Disposition: attachment; filename='.basename($local_request_file));
- }
- }
-
- }
-
- $html = '';
- $code = '';
- $this->HttpStatusCode($local_request_file, $headers, $html, $code);
-
- if($availableRequests > 0) {
- $headers[4] = "연결: 연결 유지";
- $headers[5] = '연결 유지: timeout='.$timeout.', max='.$maxRequests;
- }
-
-
- $headers[6] = '콘텐츠 길이: '. strlen($html);
-
- $response = array(
- 'header'=> implode("rn", $headers) . "rn",
- 'html'=> $html);
-
- socket_write($connfd, implode("rn", $response));
-
- if($availableRequests <= 0) {
- socket_close($connfd);
- $session = 0;
- }
-
- $length = strlen($html);
-
- 소켓_getpeername($connfd, $address, $port);
- 로그(sprintf('%s:%.0f -- " %s %s %s" %s %.0f "-" "%s"',
- $address,
- $port,
- $http_request_method,
- '/'.$http_request_file,
- $http_protocol,
- $code,
- $length,
- $http_user_agent));
- //logs('times '.intval($clients - 1), false);
- }
- }
-
- }
-
- 공개 함수 error_page($statusCode, $ServerTokens) {
-
- $httpStatus = array('403'=> '403 금지됨' , '404'=> '404 찾을 수 없음');
- $string = "
-
- %s
- < /head>
-
-
%s
- <시간 />
- %s< ;/center>
-
- ";
-
- if(!in_array($ServerTokens, array('on', 'off')))
- $ServerTokens = 'off';
-
- 반환(문자열) sprintf($string,
- $httpStatus[$statusCode],
- $httpStatus[$statusCode],
- $ServerTokens == '끄다' ? 'PHP-CLI/1.0' : 'PHP-CLI');
-
- }
-
- 공개 함수 HttpStatusCode($file, &$headers, &$html, &$code) {
-
- $code = '200';
- if(!file_exists($file)) {
- $headers[0] = 'HTTP/1.1 404 찾을 수 없음';
- $html = $this ->error_page('404', $this->arguments['ServerTokens']);
- $code = '404';
- return 0;
- }
-
- if( is_dir($file)){
- $find = false;
- $directoryIndex = $this->arguments['DirectoryIndex'];
- if(empty($directoryIndex)) {
- $headers [0] = 'HTTP/1.1 403 금지됨';
- $code = '403';
- }else{
- $list = 폭발(' ', $directoryIndex);
- foreach($list as $index) {
- if(file_exists($file .'/'. $index)) {
- $file .= '/'. $index;
- if(file_exists($file) && is_file($file))
- $extension = pathinfo($file, PATHINFO_EXTENSION);
- $array_key_exists = array_key_exists($extension, $this-> 인수['MimeTypes']);
- if($array_key_exists) {
- $mime_types = $this->arguments['MimeTypes'][$extension];
- }else{
- $this ->otect_stream = true;
- $headers[3] = sprintf('Content-Type: application/octet-stream');
- array_push($headers, 'Accept-Ranges: bytes');
- array_push($headers, 'Accept-Length: '.filesize($local_request_file));
- array_push($headers, 'Content-Disposition: attachment; filename='.basename($local_request_file));
- }
- $find = true;
- break;
- }
- }
- }
-
- if(!$find) {
- $html = $this->error_page ('403', $this->arguments['ServerTokens']);
- }else{
- if(!$this->octet_stream)
- $headers[3] = sprintf('Content -유형: %s; charset=%s', $mime_types, 'utf-8');
- $html = $this->get_local_handle_buffer($file);
- }
-
- 반환 -1;
-
- }else{
-
- $html = $this->get_local_handle_buffer($file);
-
- }
-
- return 1;
- }
-
- 공용 함수 get_local_handle_buffer($file) {
- $handle = fopen($file, 'rb');
- return $this->get_buffer($handle);
- }
-
- 공용 함수 get_buffer($handle) {
- $buffer = '';
- if(!is_resource($handle)) return null;
- while(!feof($handle) )
- $buffer .= fgets($handle, 1024);
- fclose($handle);
- return $buffer;
- }
-
- }
-
- 함수 gmtdate() {
- (문자열) date('D, d M Y H:i:s')를 반환합니다. ' GMT';
- }
-
- 함수 로그($string, $perfix = true) {
- ob_start();
- echo $perfix ?
- sprintf("[ %s ] %sn", date('d-M-Y H:i:s'), $string) :
- sprintf(" [ %s ]n", $string);
-
- ob_end_flush();
-
- }
-
- $mime_types = array(
- 'htm'=> 'text/html',
- 'html'=> 'text/html',
- 'jpg'=> 'image/jpeg',
- 'jpeg'=> 'image/jpeg',
- 'png'=> 'image/png',
- 'js'=> ,
- 'css'=> 'text/css',
- 'xml'=> 'text/xml');
-
- $conf = array(
- 'MimeTypes'= > $mime_types,
- 'ServerTokens'=> 'on',
- 'MaxRequests'=> 100,
- 'Timeout'=> ,
- 'DocumentRoot'=> '/home/www',
- 'DirectoryIndex'=> 'index.htm index.html');
-
- error_reporting(E_ALL);
- logs('운영 환경 초기화');
- sleep(1);
-
- set_time_limit(0);
- logs('PHP-CLI 실행 시간 초과 초기화');
- sleep(1 );
-
- $socket = 소켓_create(AF_INET, SOCK_STREAM, SOL_TCP);
- logs('소켓 초기화 중');
- sleep(1);
-
- logs('초기화 로컬 주소를 모든 IP 주소에 바인딩');
- sleep(1);
-
- $int = 소켓_bind($socket, '0.0.0.0', $conf['Listen']);
- logs ('초기화 바인드 로컬 포트 '.$conf['Listen']);
- if(!$int){
- logs($conf['Listen'].' 포트가 다른 서비스에 의해 사용되고 있습니다.'" n");
- exit(0);
- }
- sleep(1);
-
- socket_listen($socket, 1024);
- logs('소켓 열기 듣기') ;
- sleep(1);
-
- logs('클라이언트 액세스 대기 중');
- echo "n";
- $i = 0;
-
- while( 1) {
- $pthread[$i] = new pthread($socket, $conf);
- $pthread[$i]->start();
- $pthread[$i]-> ;join();
- }
-
-
复代码
|