swoole (8) http service

Summary:

swoole built to achieve a simple httpServer class .swoole equivalent of http server php-fpm. The biggest advantage is that high-performance, load the code only once

 

  1. http_server essentially swoole_server, but the fixed part of the protocol used in the analysis is the http protocol analysis
  2. Complete http protocol requests are parsed and the objects packaged in swoole_http_request
  3. All http responses are encapsulated and transmitted through the object swoole_http_response 

 Code:

? < PHP
 / * * 
 * PhpStorm the Created by. 
 * The User: huahua 
 * a Date: 2020/3/10 
 * Time: 2:09 PM 
 * / 

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

$ Server -> SET ([
     'pack_max_length' => 1024 * 1024 * 2, 
    . 'the upload_tmp_dir' => __ the DIR __ "/ Upload", 
    'DOCUMENT_ROOT' => __ DIR__, 
    'enable_static_handler' => to true , 
]); 
/ / onRequest callback takes two parameters are swoole_http_request swoole_http_response objects and objects, and are responsible for request response in response to requests 
$ Server -> ON ( 'request',function($request,the Response $ ) {
 // swoole_http_request, responsible for information http request. On this subject we can obtain header \ server \ get \ post \ files \ cookie and other information, superglobals This is equivalent to php's 
    $ uri = $ Request -> Server [ 'REQUEST_URI' ];
     IF ( $ uri == '/favicon.ico' ) {
         $ Request -> Status (404 );
         $ Request -> End (); 
    } 

    echo   . __DIR __ "/ Upload" ;
 // swoole_http_response handles HTTP response messages 
    $ response -> header ( "the Content The -type "," text / HTML " );
     $ the Response -> header( "The Charset", "UTF-. 8" );
     $ Response -> Cookie ( 'User', 'Peter' );
     // Please in end () before setting the respective response header, status, etc., end the operation will be The client browser sends content, and the destruction of request / response objects 
    $ the Response -> end ( "the Hello" ); 
}); 
$ Server -> Start ();

 Achieve warm restart:

<?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 (); 
        } the else {
             $ the this -> reload ();
             $ Response -> End ( 'Test' ); 
        } 
    } 

    / * * 
     * loading warm restart (the file hash value ratio) 
     * / 
    public  function reload () { 
        swoole_timer_tick ( 3000, function () {
             $ MD5 = $ the 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  $ the dir ) {
             $ MD5 . :: = Self md5File ( $ the dir ); 
        } 
        return  $ MD5 ; 
    } 

    public  static  function md5File ( $ the dir ) { 

        // all files in the folder which obtain all the files the md5 hash value 
        IF (! is_dir ( $ the dir )) {
             return '' ; 
        } 
        $ md5File = Array ();
         $ D = the dir ( $ the dir );
         the while ( to 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();

result:

 Multi-port monitoring:

<?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);   // Get the connection information 
    IF ( $ info [ 'SERVER_PORT'] == '9502' ) {
         echo "ADMIN" ; 
    } 
}); 
$ Server -> Start ();
<? PHP
 $ HTTP_Server = new new swoole_http_server ( '0.0.0.0', 9998 );
 $ HTTP_Server -> SET ( Array ( 'to daemonize' => to false ));
 $ HTTP_Server -> ON ( 'Request', function () {
     var_dump ( 'Request' ); 
}); 
// ...... settings for each callback ...... 
// more than a listening tcp port, external open tcp service, and set a callback server tcp 
$ tcp_server = $ HTTP_Server -> addListener ( '0.0.0.0', 9999, SWOOLE_SOCK_TCP);
 // default port 9999 to listen new settings will inherit the main server, but also the Http protocol 
// call the set method to cover the primary server 
$ tcp_server -> set ( array());
$tcp_server->on("receive", function ($serv, $fd, $threadId, $data) {
    echo $data;
});

$http_server->start();

 

Guess you like

Origin www.cnblogs.com/8013-cmf/p/12454651.html