PHP implementation of simple HTTP server based on droole

It Abu 2020-11-07 22:16:41
php implementation simple http server


quote Swoole The official definition of :

PHP The asynchrony of language 、 parallel 、 High performance network communication framework , Use pure C Language writing , Provides PHP Asynchronous multithreaded server of language , asynchronous TCP/UDP Network client , asynchronous MySQL, Database connection pool ,AsyncTask, Message queue , Millisecond timer , Asynchronous file read and write , asynchronous DNS Inquire about .Swoole Can be widely used in the Internet 、 mobile communication 、 Enterprise software 、 Cloud computing 、 Network game 、 The Internet of things 、 Car networking 、 Smart home and other fields . Use PHP+Swoole As a network communication framework , Can make the enterprise IT The efficiency of the R & D team has been greatly improved , More focus on developing innovative products .

Briefly here swoole Two kinds of API Write simple HTTP The server .

swoole_server

Use swoole_server API, structure HTTP The server ,4 A step :

  1. structure Server object
  2. Set run-time parameters
  3. Register event callback function
  4. Start the server

Direct code embodies , newly build server.php

<?php
//1. structure Server object
$serv = new swoole_server("0.0.0.0", 9501);
//2. Set run-time parameters
$serv->set(array(
'worker_num' => 8,
'daemonize' => 0,
'max_request' => 10000,
'dispatch_mode' => 2,
'debug_mode'=> 1,
));
//3. Register event callback function
$serv->on('Receive', function($serv, $fd, $from_id, $data){
$respData='<h1>Hello Swoole.</h1>';
response($serv,$fd,$respData);// Encapsulate and send HTTP response message
});
//4. Start the server
$serv->start();

How to package HTTP response message ? First you have to know HTTP The structure of the response message , Here's the picture

 Insert picture description here

Know the structure of the response message , Then my response message should be like this :

HTTP/1.1 200
Server:SwooleServer
Content-Type:text/html;charset=utf8
Content-Length:13
<h1>Hello Swoole.</h1>

Code implementation .


/**
* send content
* @param \swoole_server $serv
* @param int $fd
* @param string $respData
* @return void
*/
function response($serv,$fd,$respData){
// Response line
$response = array(
'HTTP/1.1 200',
);
// Response head
$headers = array(
'Server'=>'SwooleServer',
'Content-Type'=>'text/html;charset=utf8',
'Content-Length'=>strlen($respData),
);
foreach($headers as $key=>$val){
$response[] = $key.':'.$val;
}
// Blank line
$response[] = '';
// Response body
$response[] = $respData;
$send_data = join("\r\n",$response);
$serv->send($fd, $send_data);
}

Here we are , A simple response Hello Swoole. Of HTTP The server is done . Complete code : here
( I can't visit gist? Configure local hosts file : 192.30.252.141 gist.github.com )

function php server.php, Browser access http://127.0.0.1:9501/, Of course, we often use Nginx As a front-end agent , Set up a test domain name www.server.com, Local settings hosts mapping , You can access it through your domain name .Nginx To configure : here
Be careful : When the response message format is not correct , The browser page will always turn chrysanthemum , Wait for the request to return ...

later , With swoole_http_server,HTTP The server code becomes simpler !

swoole_http_server

<?php
$http = new swoole_http_server("127.0.0.1", 9501);
$http->on('request', function ($request, $response) {
$html = "<h1>Hello Swoole.</h1>";
$response->end($html);
});

you 're right , In just a few lines of code . No need to encapsulate the response message .swoole_http_server Inherited from swoole_server, yes swoole built-in Http Server support , In a few lines of code, you can write an asynchronous non blocking multiprocessor Http The server .

Notice:swoole_http_server Yes Http Support for the agreement is not complete , Recommended as an application server only . And add... At the front end Nginx Acting as agent

Focus , Neverlost

All right, everyone , The above is the whole content of this article , You can see the people here , All are personnel . I said before ,PHP There are many technical points in this aspect , It's also because there are so many , I can't write it down , We won't read too much after writing it , So I've organized it into PDF And documentation , If you need anything, you can

Click to enter the code : PHP+「 platform 」

 Insert picture description here

 Insert picture description here


More learning can be found in 【 Benchmarking big factories 】 The high-quality goods PHP Architect tutorial catalog , As long as you can finish it, make sure your salary goes up one step ( Continuous updating )

I hope the above will help you , quite a lot PHPer There are always some problems and bottlenecks in the advanced stage , There is no sense of direction in the business code , I don't know where to start to improve , I've compiled some information about it , Including but not limited to : Distributed architecture 、 Highly scalable 、 High performance 、 High concurrency 、 Server performance tuning 、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql Optimize 、shell Script 、Docker、 Microservices 、Nginx If you need advanced advanced dry goods, you can share them for free , You can join me if you need PHP Technology exchange group

版权声明
本文为[It Abu]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple