swoole(8)http服务

简介:

swoole内置实现了一个简单的httpServer类.swoole的http server相当于php-fpm.最大优势在于高性能,代码只载入一次

  1. http_server本质是swoole_server,不过在协议的解析部分固定使用的是http协议解析
  2. 完整的http协议请求会被解析并封装在swoole_http_request对象中
  3. 所有的http响应都通过swoole_http_response对象进行封装和发送 

 代码:

<?php
/**
 * Created by PhpStorm.
 * User: huahua
 * Date: 2020/3/10
 * Time: 下午2:09
 */

$server = new \Swoole\Http\Server('0.0.0.0',9800);

$server->set([
    'pack_max_length'=>1024*1024*2,
    'upload_tmp_dir'=>__DIR__."/upload",
    'document_root' =>__DIR__,
    'enable_static_handler' => true,
]);
//onRequest回调接收两个参数分别是swoole_http_request对象和swoole_http_response对象,分别负责request请求和response响应
$server->on('request',function($request,$response){
//swoole_http_request,负责http请求的相关信息。我们可以在这个对象上,获取header\server\get\post\files\cookie等信息,这等同于php的超全局变量
    $uri = $request->server['request_uri'];
    if ($uri == '/favicon.ico') {
        $request->status(404);
        $request->end();
    }

    echo  __DIR__."/upload";
//swoole_http_response负责处理HTTP响应信息
    $response->header("Content-type","text/html");
    $response->header("Charset","utf-8");
    $response->cookie('user','peter');
    //请在end()之前设置相应的响应头、状态等等,end操作后将向客户端浏览器发送内容,并销毁request/response对象
    $response->end("hello");
});
$server->start();

 实现热重启:

<?php
/**
 * Created by PhpStorm.
 * User: huahua
 * Date: 2020/3/17
 * Time: 下午4:50
 */

namespace Six;

use Swoole\Http\Server;

class App {
    protected $server;

    public static $rootPath;
    public static $framePath;
    public static $applicationPath;

    protected $watch_path;

    protected $md5File;

    public function run() {
        self::$rootPath = dirname(dirname(__DIR__));
        self::$framePath = self::$rootPath . '/framework';
        self::$applicationPath = self::$rootPath . '/application';

        $this->watch_path = [self::$framePath, self::$applicationPath];
        $this->md5File = $this->getMd5();

        $this->server = new Server('0.0.0.0', 9800);
        $this->server->set([
            'pack_max_length' => 1024 * 1024 * 2,
            'worker_num' => 3,
        ]);

        $this->server->on('request', [$this, 'request']);
        $this->server->on('Start', [$this, 'start']);
        $this->server->on('workerStart', [$this, 'workerStart']);
        $this->server->start();
    }

    public function request($request, $response) {
        $uri = $request->server['request_uri'];
        if ($uri == '/favicon.ico') {
            $response->status(404);
            $response->end();
        } else {
            $this->reload();
            $response->end('test');
        }
    }

    /**
     *加载热重启(比对文件的散列值)
     */
    public function reload() {
        swoole_timer_tick(3000,function(){
            $md5 = $this->getMd5();
            if ($md5 != $this->md5File){
                $this->server->reload();
                $this->md5File = $md5;
            }
        });
    }

    public function start() {
        $this->reload();
    }

    public function workerStart($server, $worker_id) {


    }

    public function getMd5() {
        $md5 = '';

        foreach ($this->watch_path as $dir) {
            $md5 .= self::md5File($dir);
        }
        return $md5;
    }

    public static function md5File($dir) {

        //遍历文件夹当中的所有文件,得到所有的文件的md5散列值
        if (!is_dir($dir)) {
            return '';
        }
        $md5File = array();
        $d = dir($dir);
        while (false !== ($entry = $d->read())) {

            if ($entry !== '.' && $entry !== '..') {
                if (is_dir($dir . '/' . $entry)) {
                    //递归调用
                    $md5File[] = self::md5File($dir . '/' . $entry);
                } elseif (substr($entry, -4) === '.php') {
                    $md5File[] = md5_file($dir . '/' . $entry);
                }
                $md5File[] = $entry;
            }
        }
        $d->close();
        return md5(implode('', $md5File));
    }
}

test.php

<?php
/**
 * Created by PhpStorm.
 * User: huahua
 * Date: 2020/3/17
 * Time: 下午4:48
 */

require_once  dirname(__DIR__).'/vendor/autoload.php';

$app = new \Six\App();
$app->run();

结果:

 多端口监听:

<?php
/**
 * Created by PhpStorm.
 * User: huahua
 * Date: 2020/3/18
 * Time: 下午5:42
 */

$server=new Swoole\Server('0.0.0.0',9800);

$server->set([
]);

$server->listen('127.0.0.1', 9502, SWOOLE_SOCK_TCP); //必须在start之前
$server->on('receive',function ($serv, $fd, $from_id, $data){
    $info=$serv->connection_info($fd,$from_id);  //获取连接信息
    if($info['server_port']=='9502'){
        echo "admin";
    }
});
$server->start();
<?php
$http_server = new swoole_http_server('0.0.0.0',9998);
$http_server->set(array('daemonize'=> false));
$http_server->on('request',function(){
    var_dump('request');
});
//......设置各个回调......
//多监听一个tcp端口,对外开启tcp服务,并设置tcp服务器的回调
$tcp_server = $http_server->addListener('0.0.0.0', 9999, SWOOLE_SOCK_TCP);
//默认新监听的端口 9999 会继承主服务器的设置,也是 Http 协议
//需要调用 set 方法覆盖主服务器的设置
$tcp_server->set(array());
$tcp_server->on("receive", function ($serv, $fd, $threadId, $data) {
    echo $data;
});

$http_server->start();

猜你喜欢

转载自www.cnblogs.com/8013-cmf/p/12454651.html