PHP+Swoole实现简单HTTP服务器

Swoole

swoole官方文档 https://wiki.swoole.com

Swoole 是一个 PHP 的 协程 高性能 网络通信引擎,使用 C/C++ 语言编写,提供了多种通信协议的网络服务器和客户端模块。可以方便快速的实现 TCP/UDP服务、高性能Web、WebSocket服务、物联网、实时通讯、游戏、微服务等,使 PHP 不再局限于传统的 Web 领域。

PHP+Swoole实现简单HTTP服务器

swoole官方提供Http服务器基础demo

$http = new Swoole\Http\Server("127.0.0.1", 9501);

$http->on("start", function ($server) {
    echo "Swoole http server is started at http://127.0.0.1:9501\n";
});

$http->on("request", function ($request, $response) {
    $response->header("Content-Type", "text/plain");
    $response->end("Hello World\n");
});

$http->start();

我们在此基础上进行调整优化

首先, 以面向对象的思想封装成类的形式

class Http
{
	private $http;
	 
	public function __construct() {
	 	// 绑定端口
	 	$this->http = new \Swoole\Http\Server('0.0.0.0', 9501);
	 	// 绑定回调方法
	 	$this->http->on('request', [$this, 'onRequest']); 	
		//启动服务
	 	$this->http->start();
	}
	
	public function onRequest($request, $response) {
		$response->header("Content-Type", "text/plain");
	    $response->end("Hello World\n");
	}
}

继续完善
排除ico图标请求

if($request->server['request_uri'] == '/favicon.ico') {
	$response->status(404);
	$response->end();
	return ;
}

swoole搭建Http服务器接收到请求信息会保存在onRequest回调方法中的$request中, 其中包括get、post、server、header和files数据。在原生或框架中, 一般都是通过$_SERVER, $_POST等超全局变量中获得的。因此我们也对按照这种使用习惯进行简单封装

$_POST = [];
if (isset($request->post)) {
    foreach ($request->post as $key => $value) {
        $_POST[strtoupper($key)] = $value;
    }
}
$_GET = [];
if (isset($request->get)) {
    foreach ($request->get as $key => $value) {
        $_GET[strtoupper($key)] = $value;
    }
}
$_SERVER = [];
if (isset($request->server)) {
    foreach ($request->server as $key => $value) {
        $_SERVER[strtoupper($key)] = $value;
    }
}
if (isset($request->header)) {
    foreach ($request->header as $key => $value) {
        $_SERVER[strtoupper($key)] = $value;
    }
}
$_FILES = [];
if (isset($request->files)) {
    foreach ($request->files as $key => $value) {
        $_FILES[strtoupper($key)] = $value;
    }
}

因为Swoole是常驻内存的, 需要$_XXX = []; 进行初始化, $request->xxx 有可能取到NULL值, 要先判断是否存在。

通过ob缓存获取内容(不然会数据会输出到控制台), 最后返回数据(需要对可能产出错误的的代码进行异常捕获, 不然会引起Swoole进程退出)

try {
	ob_start();
	
	// 这里可以自己实现方法调用 或 引用框架的内核进行数据处理(需引入composer加载、框架核心类加载)
	
	$result = ob_get_contents();
	ob_end_clean();
	
	$response->header('Content-Type', 'text/html');
	$response->header('Charset', 'utf-8');
	$response->end($result);
} catch (\Execption $e) {
	// TODO 输出异常信息 记录日志等
}

设置Http服务的常用参数(部分)

$this->http->set([
	 'enable_static_handler' => true,
     'document_root'         => __DIR__ . '/public/static',
     'worker_num'            => 8,
     'max_request' 	   	     => 3000
]);

enable_static_handler 排除静态文件(排除后不会触发onRequest事件)
document_root 加载静态文件目录, 当有静态文件请求就会到此目录中寻找
worker_num 设置worker数量, worker是什么应该不用说了吧…
max_request 最大请求数, 当请求数超过设置的数值就会kill掉worker由Manager进程重启拉起新的worker, 主要是用来防止由于代码编写不当而产生的少量内存溢出问题(大量溢出怕是得好好检查代码了)

下面是完整的代码, 我引入了composer自动加载并进行简单路由

<?php
require_once __DIR__ . '/vendor/autoload.php';

/**
 * Http服务器
 * Class Http
 */
class Http
{
    private $http;
    public function __construct()
    {
        $this->http = new \Swoole\Http\Server('0.0.0.0', 9501);
        $this->http->on('request', [$this, 'onRequest']);
        $this->http->set([
            'enable_static_handler' => true,
            'document_root'            => __DIR__ . '/public/static',
            'worker_num'                => 8,
            'max_request' 			     => 3000
        ]);
        $this->http->start();
    }

    public function onRequest($request, $response)
    {
        // 拒绝ico请求
        if($request->server['request_uri'] == '/favicon.ico') {
            $response->status(404);
            $response->end();
            return ;
        }

        $_POST = [];
        if (isset($request->post)) {
            foreach ($request->post as $key => $value) {
                $_POST[strtoupper($key)] = $value;
            }
        }
        $_GET = [];
        if (isset($request->get)) {
            foreach ($request->get as $key => $value) {
                $_GET[strtoupper($key)] = $value;
            }
        }
        $_SERVER = [];
        if (isset($request->server)) {
            foreach ($request->server as $key => $value) {
                $_SERVER[strtoupper($key)] = $value;
            }
        }
        if (isset($request->header)) {
            foreach ($request->header as $key => $value) {
                $_SERVER[strtoupper($key)] = $value;
            }
        }
        $_FILES = [];
        if (isset($request->files)) {
            foreach ($request->files as $key => $value) {
                $_FILES[strtoupper($key)] = $value;
            }
        }

        $pathInfo = $request->server['path_info'];

        // 处理path_info
        if ($pathInfo != '/') {
            if ($a = strrpos($pathInfo,'.')) {
                $pathInfo = substr($pathInfo, 0, $a-strlen($pathInfo));
            }
            $pathInfo = trim($pathInfo, '/');
            $pathInfo = explode('/', $pathInfo);

        }

        if (is_array($pathInfo)) {
            $model = $pathInfo[0] ?? 'Index';
            $controller = $pathInfo[1] ?? 'Index';
            $method = $pathInfo[2] ?? 'index';
        }
//
        $params = [];
        $classNme = "\\App\\Https\\{$model}\\Controllers\\{$controller}";
        try {
            ob_start();
            // 通过反射机制获取
            $class = (new ReflectionClass($classNme))->newInstanceArgs($params);
            $class->$method();
            $result = ob_get_contents();
            ob_end_clean();
            $response->header('Content-Type', 'text/html');
            $response->header('Charset', 'utf-8');
            $response->end($result);
        } catch (\Exception $e) {
        	// 调试 输出错误
            echo $e->getMessage();
        }

    }
}

由于Swoole的Http服务对http协议支持并不完整, 因此仅建议作为应用服务器, 并且在前端增加Nginx进行代理. Nginx配置:

server {
    listen 80;
    server_name 域名;

    access_log 域名.access.log  main;
    error_log  域名.error.log;

    location / {
        proxy_http_version 1.1;
        proxy_set_header Connection "keep-alive";
        # 带上请求客户端真实IP
        proxy_set_header REMOTE-HOST $remote_addr;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        # 地址加端口
        proxy_pass ip:9501;
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值