Table of Contents
使用方式
301 Moved
性能
Home Backend Development PHP Tutorial 可用于实现纯异步PHP程序:php_http_parser

可用于实现纯异步PHP程序:php_http_parser

Jun 23, 2016 pm 01:20 PM

php_http_parser 是基于node.js http-parser的PHP扩展,可用于实现纯异步PHP程序

libcurl提供了异步调用方式,有两种风格:

  • ONE MULTI HANDLE MANY EASY HANDLES:加入多个easy handle后执行curl_multi_perform方法。该方法在php curl扩展中有对应实现。但最后一步curl_multi_perform是阻塞的。

  • MULTI_SOCKET,这个是真正的非阻塞方法,但需要自行实现event loop,且封装较为困难,目前在php中没有对应实现。经过调研,curl_multi_socket_action跟php内核结合困难度很高。

除此之外,基本上没有真正的实现异步http请求的php扩展。目前仅有部分纯php实现的版本,比如tsf中的http client实现。 使用纯php实现的问题主要受限于http解析的性能。因此考虑将这一模块用扩展的方式来实现。node.js http-parser就是一个很好的c语言的http解析库。 php_http_parser就是对其做的一个封装,在php中暴露出相应的接口。

为了实现真正的非阻塞请求,仍然需要自己实现event loop。目前推荐结合swoole使用,以获得更好的性能。

使用方式

$buffs = array("HTTP/1.1 301 Moved Permanently\r\n","Location: http://www.google.com/\r\n","Content-Type: text/html; charset=UTF-8\r\n","Date: Sun, 26 Apr 2009 11:11:49 GMT\r\n","Expires: Tue, 26 May 2009 11:11:49 GMT\r\n","Cache-Control: public, max-age=2592000\r\n","Server: gws\r\n","Content-Length: 193\r\n","\r\n","<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n","<TITLE>301 Moved</TITLE></HEAD><BODY>\n","<h1 id="nbsp-Moved">301 Moved</h1>\n","The document has moved\n","<A HREF=\"http://www.google.com/\">here</A>.\r\n"    ,"<A HREF=\"http://www.google.com/\">here</A>.\r\n"    ,"<A HREF=\"http://www.google.com/\">here</A>.\r\n"    ,"<A HREF=\"http://www.google.com/\">here</A>.\r\n"    ,"<A HREF=\"http://www.google.com/\">here</A>.\r\n","</BODY></HTML>\r\n");$hp = new HttpParser();foreach($buffs as $buff){    $ret = $hp->execute($buff);    if($ret !== false){        echo $ret;        break;    }}
Copy after login

虽然http请求可能分包发送,HttpParser会将所有包合并在一起后,出发body事件,然后调用相应的回调方法。 诸如header回调,目前暂未实现。另外,此处需要自行实现timeout逻辑。

示例代码是结合swoole_client与swPromise框架实现的一个异步http client。 籍此可以实现真正的非阻塞的PHP程序。

class HttpClientFuture implements FutureIntf {    protected $url = null;    protected $post = null;    protected $proxy = false;    public function __construct($url, $post = array(), $proxy = array()) {        $this->url = $url;        $this->post = $post;        if($proxy){            $this->proxy = $proxy;        }    }    public function run(Promise &$promise) {        $cli = new \swoole_client ( SWOOLE_TCP, SWOOLE_SOCK_ASYNC );        $urlInfo = parse_url ( $this->url );        if(!isset($urlInfo ['port']))$urlInfo ['port'] = 80;        $httpParser = new \HttpParser();        $cli->on ( "connect", function ($cli)use($urlInfo){            $host = $urlInfo['host'];            if($urlInfo['port'])$host .= ':'.$urlInfo['port'];            $req = array();            $req[] = "GET {$this->url} HTTP/1.1\r\n";            $req[] = "User-Agent: PHP swAsync\r\n";            $req[] = "Host:{$host}\r\n";            $req[] = "Connection:close\r\n";            $req[] = "\r\n";            $req = implode('', $req);            $cli->send ( $req );        } );        $cli->on ( "receive", function ($cli, $data = "") use(&$httpParser, &$promise) {            $ret = $httpParser->execute($data);            if($ret !== false){                $cli->close();                $promise->accept(['http_data'=>$ret]);            }        } );        $cli->on ( "error", function ($cli) use(&$promise) {            $promise->reject ();        } );        $cli->on ( "close", function ($cli) {        } );        if($this->proxy){            $cli->connect ( $this->proxy['host'], $this->proxy ['port'], 1 );        }else{            $cli->connect ( $urlInfo ['host'], $urlInfo ['port'], 1 );        }    }}
Copy after login

性能

[web@gz-web01 php_http_parser]$ time /data/server/php/bin/php http_parser.php  2000000real    0m11.489suser    0m11.435ssys 0m0.017s
Copy after login

1个worker进程

./http_load -fetches 20000 -parallel 100 9502.listasync 20000 fetches, 100 max parallel, 2.02e+06 bytes, in 5.94536 seconds101 mean bytes/connection3363.97 fetches/sec, 339761 bytes/secmsecs/connect: 0.0473873 mean, 1.155 max, 0.019 minmsecs/first-response: 29.6366 mean, 51.736 max, 15.22 minHTTP response codes:code 200 -- 20000-bash: history: write error: Success
Copy after login

2个worker进程

./http_load -fetches 20000 -parallel 100 9502.listasync 20000 fetches, 100 max parallel, 2.02e+06 bytes, in 3.17119 seconds101 mean bytes/connection6306.77 fetches/sec, 636984 bytes/secmsecs/connect: 0.0643583 mean, 1.211 max, 0.023 minmsecs/first-response: 15.7489 mean, 32.425 max, 3.242 minHTTP response codes:code 200 -- 20000-bash: history: write error: Success
Copy after login

4个woker进程

./http_load -fetches 20000 -parallel 100 9502.listasync 20000 fetches, 100 max parallel, 2.02e+06 bytes, in 1.57194 seconds101 mean bytes/connection12723.2 fetches/sec, 1.28504e+06 bytes/secmsecs/connect: 0.0815263 mean, 1.349 max, 0.02 minmsecs/first-response: 7.65904 mean, 22.568 max, 1.221 minHTTP response codes:code 200 -- 20000-bash: history: write error: Success
Copy after login

8个woker进程

./http_load -fetches 20000 -parallel 100 9502.listasync 20000 fetches, 100 max parallel, 2.02e+06 bytes, in 1.02967 seconds101 mean bytes/connection19423.8 fetches/sec, 1.9618e+06 bytes/secmsecs/connect: 0.147502 mean, 1.575 max, 0.014 minmsecs/first-response: 3.17218 mean, 22.566 max, 0.339 minHTTP response codes:code 200 -- 20000-bash: history: write error: Success
Copy after login

官方网站:http://www.open-open.com/lib/view/home/1451808838620

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

See all articles