Home  >  Article  >  Backend Development  >  PHP实现基于Swoole简单的HTTP服务器

PHP实现基于Swoole简单的HTTP服务器

WBOY
WBOYOriginal
2016-06-20 12:41:06952browse

引用Swoole官方定义:

PHP语言的异步、并行、高性能网络通信框架,使用纯C语言编写,提供了PHP语言的异步多线程服务器,异步TCP/UDP网络客户端,异步MySQL,数据库连接池,AsyncTask,消息队列,毫秒定时器,异步文件读写,异步DNS查询。Swoole可以广泛应用于互联网、移动通信、企业软件、云计算、网络游戏、物联网、车联网、智能家居等领域。使用PHP+Swoole作为网络通信框架,可以使企业IT研发团队的效率大大提升,更加专注于开发创新产品。

在这里简述swoole两种API编写简单HTTP服务器。

swoole_server

使用swoole_server API,构建HTTP服务器,4个步骤:

  1. 构建Server对象
  2. 设置运行时参数
  3. 注册事件回调函数
  4. 启动服务器

直接代码体现,新建 server.php

<?php//1.构建Server对象$serv = new swoole_server("0.0.0.0", 9501);//2.设置运行时参数$serv->set(array(    'worker_num' => 8,    'daemonize' => 0,    'max_request' => 10000,    'dispatch_mode' => 2,    'debug_mode'=> 1,));//3.注册事件回调函数$serv->on('Receive', function($serv, $fd, $from_id, $data){    $respData='<h1>Hello Swoole.</h1>';    response($serv,$fd,$respData);//封装并发送HTTP响应报文});//4.启动服务器$serv->start();

如何封装HTTP响应报文?首先你得知道HTTP响应报文的组成结构,如下图

知道了响应报文的组成结构,那我的响应报文应该是这样的:

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

代码实现。

/*** 发送内容* @param \swoole_server $serv* @param int $fd* @param string $respData* @return void*/function response($serv,$fd,$respData){    //响应行    $response = array(        'HTTP/1.1 200',    );    //响应头    $headers = array(        'Server'=>'SwooleServer',        'Content-Type'=>'text/html;charset=utf8',        'Content-Length'=>strlen($respData),    );    foreach($headers as $key=>$val){        $response[] = $key.':'.$val;    }    //空行    $response[] = '';    //响应体    $response[] = $respData;    $send_data = join("\r\n",$response);    $serv->send($fd, $send_data);}

到此,一个简单响应 Hello Swoole. 的HTTP服务器就完成了。完整代码: 这里

(访问不了gist?配置本地hosts文件: 192.30.252.141 gist.github.com )

运行 php server.php ,浏览器访问http://127.0.0.1:9501/,当然我们常常使用Nginx作为前端代理,设一个www.server.com,本地设置hosts映射,就能通过域名来访问了。Nginx配置: 这里

注意:当响应报文格式不正确时,浏览器页面会一直转菊花,等待请求返回...

再后来,有了swoole_http_server,HTTP服务器代码就变得更加简单了!

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);});

没错,就这几行代码就实现了。不再需要封装响应报文。swoole_http_server 继承于 swoole_server,是swoole内置Http服务器的支持,通过几行代码即可写出一个异步非阻塞多进程的Http服务器。

Notice:swoole_http_server对Http协议的支持并不完整,建议仅作为应用服务器。并且在前端增加Nginx作为代理

参考

  • http://www.swoole.com/
  • https://github.com/LinkedDestiny/swoole-doc
Statement:
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