PHP+Swoole实现简单HTTP服务器_php http登陆并通讯-程序员宅基地

技术标签: nginx  linux  php  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;
    }
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_39817726/article/details/105942372

智能推荐

数据的两种归一化方法_数据量级相差较大 归一化-程序员宅基地

文章浏览阅读1.3k次。数据标准化(归一化)处理是数据挖掘的一项基础工作,不同评价指标往往具有不同的量纲和量纲单位,这样的情况会影响到数据分析的结果,为了消除指标之间的量纲影响,需要进行数据标准化处理,以解决数据指标之间的可比性。原始数据经过数据标准化处理后,各指标处于同一数量级,适合进行综合对比评价。一般而言,数据的标准化(normalization)是将数据按比例缩放,使之落入一个小的特定区间。在某些比较和评价的..._数据量级相差较大 归一化

立志进大厂的Owen-程序员宅基地

文章浏览阅读335次。为什么写博客?目录为什么写博客?​​​​​​​

图表示学习Graph Embedding:DeepWalk python实现_graph embedding python-程序员宅基地

文章浏览阅读1.1w次,点赞12次,收藏45次。https://github.com/AI-luyuan/graph-embedding_graph embedding python

【JAVA开发小技巧】使用enum枚举类规范化代码_枚举 代码规范-程序员宅基地

文章浏览阅读433次,点赞6次,收藏11次。阿里巴巴Java开发手册中推荐,如果常量类中变量值仅在一个范围内变化,且带有名称之外的延伸属性, 建议定义为枚举类。使用枚举类可以使我们的代码更加规范且美观。_枚举 代码规范

Python基础教程:strip 函数踩坑_python的rstrip为什么没用-程序员宅基地

文章浏览阅读430次。S.strip(chars=None)strip 函数用于去除字符串首尾的空格,当 chars 不为 None 时,则删除字符串首尾的 chars 中的字符。当 chars=None 时,去除首尾空格,没啥好说的,我们来看 chars 不为 None 时的情况。str = 'abc123abc'print(str.strip('a')) # bc123abcprint(str.strip('abc')) # 123结果跟预期的一样,我们再看下面的例子:'''Pyth_python的rstrip为什么没用

Kotlin 解压缩_kotlin 对上传的压缩包进行分析-程序员宅基地

文章浏览阅读638次。fun unZip(zipFile: String, context: Context) { var outputStream: OutputStream? = null var inputStream: InputStream? = null try { val zf = ZipFile(zipFile) val entries = zf.entries() while (en..._kotlin 对上传的压缩包进行分析

随便推点

<转载>Android 对sdcard操作-程序员宅基地

文章浏览阅读347次。其实就是普通的文件操作,不过还是有些地方需要注意。比如: 1.加入sdcard操作权限; 2.确认sdcard的存在; 3.不能直接在非sdcard的根目录创建文件,而是需要先创建目录,再创建文件; 在AndroidManifest.xml添加sdcard操作权限 复制代码

BDC报错信息查看-程序员宅基地

文章浏览阅读150次。3.在事务代码se91中输入对应消息类和消息编号。1.在事务代码st22的报错信息中下载本地文件。4.查看报错信息,根据报错信息取解决问题。2.打开本地文件查看报错信息。

AS 3.1.3连续依赖多个Module,导致访问不到Module中的类_为什么as在一个包下建了多个module,缺无法打开了-程序员宅基地

文章浏览阅读1.1k次。我好苦啊,半夜还在打代码。还出bug,狗日的。问题是这样的:我在新建的项目里,建了两个Module: fiora-ec和fiora-core。项目的依赖顺序是这样的,App依赖fiora-ec,fiora-ec又依赖于fiora-core,因为这种依赖关系,所有可以在app和fiora-ec中删除一些不必要的引入,比如这个玩意儿:com.android.support:appcompat-v7:..._为什么as在一个包下建了多个module,缺无法打开了

Magento 常用插件二-程序员宅基地

文章浏览阅读1.4k次。1. SMTP 插件 URL:http://www.magentocommerce.com/magento-connect/TurboSMTP/extension/4415/aschroder_turbosmtp KEY:magento-community/Aschroder_TurboSmtp 2. Email Template Adapter..._magento extension pour ricardo.ch

【连载】【FPGA黑金开发板】Verilog HDL那些事儿--低级建模的资源(六)-程序员宅基地

文章浏览阅读161次。声明:本文为原创作品,版权归akuei2及黑金动力社区共同所有,如需转载,请注明出处http://www.cnblogs.com/kingst/ 2.5 低级建模的资源 低级建模有讲求资源的分配,目的是使用“图形”来提高建模的解读性。 图上是低级建模最基本的建模框图,估计大家在实验一和实验二已经眼熟过。功能模块(低级功能模块)是一个水平的长方形,而控制模块(低级控制模块)是矩形。组..._cyclone ep2c8q208c黑金开发板

R语言实用案例分析-1_r语言案例分析-程序员宅基地

文章浏览阅读2.2w次,点赞10次,收藏63次。在日常生活和实际应用当中,我们经常会用到统计方面的知识,比如求最大值,求平均值等等。R语言是一门统计学语言,他可以方便的完成统计相关的计算,下面我们就来看一个相关案例。1. 背景最近西安交大大数据专业二班,开设了Java和大数据技术课程,班级人数共100人。2. 需求通过R语言完成该100位同学学号的生成,同时使用R语言模拟生成Java和大数据技术成绩,成绩满分为100,需要满足正_r语言案例分析