Article 80

This is the fourth article on Swoole learning: Applications of Swoole HTTP.

  • Swoole WebSocket application

  • Swoole Task application

  • Swoole Timer application

An overview of the

We all know HTTP as the protocol that allows WEB servers and browsers to send and receive data over the Internet.

For a detailed understanding of HTTP, you can find other articles, this article will not cover.

Interfaces, pictures, animations, audio, video, etc. that we can see on the Internet all depend on this protocol.

When doing WEB system, have used IIS, Apache, Nginx, we can also use Swoole simple implementation of a WEB server.

HTTP is mainly used for two objects: Request object and Response object.

Request includes GET, POST, COOKIE, and Header.

Response, including status, Response body, jump, send file, etc.

Without further comment, let’s share two apps:

  • First, implement a basic Demo: “Hello, Swoole.”

  • Second, implement a simple routing control

Local version:

  • PHP 7.2.6

  • Swoole 4.3.1

code

Demo: “Hello, Swoole.”

Example effects:

Note: The IP address is my VM.

Example code:


     

    <? php

    class Server

    {

    private $serv;

    public function __construct() {

    $this->serv = new swoole_http_server("0.0.0.0", 9502);

    $this->serv->set([

    'worker_num' => 2, // Start two worker processes

    'max_request' => 4, // set max_request to 4 times per worker process

    'daemonize' => false, // daemon (true/false)

    ]);

    $this->serv->on('Start', [$this, 'onStart']);

    $this->serv->on('WorkerStart', [$this, 'onWorkStart']);

    $this->serv->on('ManagerStart', [$this, 'onManagerStart']);

    $this->serv->on("Request", [$this, 'onRequest']);

    $this->serv->start();

    }

    public function onStart($serv) {

    echo "#### onStart ####".PHP_EOL;

    SWOOLE_VERSION. "Service started ".PHP_EOL;

    echo "master_pid: {$serv->master_pid}".PHP_EOL;

    echo "manager_pid: {$serv->manager_pid}".PHP_EOL;

    echo "########".PHP_EOL.PHP_EOL;

    }

    public function onManagerStart($serv) {

    echo "#### onManagerStart ####".PHP_EOL.PHP_EOL;

    }

    public function onWorkStart($serv, $worker_id) {

    echo "#### onWorkStart ####".PHP_EOL.PHP_EOL;

    }

    public function onRequest($request, $response) {

    $response->header("Content-Type", "text/html; charset=utf-8");

    $HTML = "<h1> Swoole.</h1>";

    $response->end($html);

    }

    }

    $server = new Server();

Copy the code

Ii. Routing control

Example effects:

Directory structure:


     

    Swoole_http - Code root

    │ ├ ─ for server PHP

    │ ├ ─ controller

    │ ├ ─ ─ Index. PHP

    │ ├ ─ ─ the Login. PHP

Copy the code

Example code:

server.php


     

    <? php

    class Server

    {

    private $serv;

    public function __construct() {

    $this->serv = new swoole_http_server("0.0.0.0", 9501);

    $this->serv->set([

    'worker_num' => 2, // Start two worker processes

    'max_request' => 4, // set max_request to 4 times per worker process

    'document_root' => '',

    'enable_static_handler' => true,

    'daemonize' => false, // daemon (true/false)

    ]);

    $this->serv->on('Start', [$this, 'onStart']);

    $this->serv->on('WorkerStart', [$this, 'onWorkStart']);

    $this->serv->on('ManagerStart', [$this, 'onManagerStart']);

    $this->serv->on("Request", [$this, 'onRequest']);

    $this->serv->start();

    }

    public function onStart($serv) {

    echo "#### onStart ####".PHP_EOL;

    swoole_set_process_name('swoole_process_server_master');

    SWOOLE_VERSION. "Service started ".PHP_EOL;

    echo "master_pid: {$serv->master_pid}".PHP_EOL;

    echo "manager_pid: {$serv->manager_pid}".PHP_EOL;

    echo "########".PHP_EOL.PHP_EOL;

    }

    public function onManagerStart($serv) {

    echo "#### onManagerStart ####".PHP_EOL.PHP_EOL;

    swoole_set_process_name('swoole_process_server_manager');

    }

    public function onWorkStart($serv, $worker_id) {

    echo "#### onWorkStart ####".PHP_EOL.PHP_EOL;

    swoole_set_process_name('swoole_process_server_worker');

    spl_autoload_register(function ($className) {

    $classPath = __DIR__ . "/controller/" . $className . ".php";

    if (is_file($classPath)) {

    require "{$classPath}";

    return;

    }

    });

    }

    public function onRequest($request, $response) {

    $response->header("Server", "SwooleServer");

    $response->header("Content-Type", "text/html; charset=utf-8");

    $server = $request->server;

    $path_info = $server['path_info'];

    $request_uri = $server['request_uri'];

    if ($path_info == '/favicon.ico' || $request_uri == '/favicon.ico') {

    return $response->end();

    }

    $controller = 'Index';

    $method = 'home';

    if ($path_info ! = '/') {

    $path_info = explode('/',$path_info);

    if (! is_array($path_info)) {

    $response->status(404);

    $response->end('URL does not exist ');

    }

    if ($path_info[1] == 'favicon.ico') {

    return;

    }

    $count_path_info = count($path_info);

    if ($count_path_info > 4) {

    $response->status(404);

    $response->end('URL does not exist ');

    }

    $controller = (isset($path_info[1]) && ! empty($path_info[1])) ? $path_info[1] : $controller;

    $method = (isset($path_info[2]) && ! empty($path_info[2])) ? $path_info[2] : $method;

    }

    $result = "class does not exist ";

    if (class_exists($controller)) {

    $class = new $controller();

    $result = "method does not exist ";

    if (method_exists($controller, $method)) {

    $result = $class->$method($request);

    }

    }

    $response->end($result);

    }

    }

    $server = new Server();

Copy the code

Index.php


     

    <? php

    class Index

    {

    public function home($request)

    {

    $get = isset($request->get) ? $request->get : [];

    // @todo business code

    $result = "<h1> Hello, Swoole. </h1>";

    $result.= "getargument: ".json_encode($GET);

    return $result;

    }

    }

Copy the code

Login.php


     

    <? php

    class Login

    {

    public function index($request)

    {

    $post = isset($request->post) ? $request->post : [];

    // @todo business code

    Return "<h1> Login successful. </h1>";

    }

    }

Copy the code

summary

Swoole to replace Nginx?

Not yet, but as Swoole grows stronger, we may not know.

Swoole is recommended to be used in conjunction with Nginx.

Http\Server has incomplete support for the Http protocol and is recommended as an application Server only. And add Nginx as a proxy on the front end.

You can adjust it according to your Nginx configuration file.

For example, you can add a configuration file

enable-swoole-php.conf


     

    location ~ [^/]\.php(/|$)

    {

    Proxy_http_version 1.1;

    proxy_set_header Connection "keep-alive";

    proxy_set_header X-Real-IP $remote_addr;

    Proxy_pass http://127.0.0.1:9501;

    }

Copy the code

We are all used to having the configuration files for virtual domain names in the vhost folder.

For example, the virtual domain name configuration file is local.swoole.com.conf. You can choose to load enable-php.conf or enable-swoole-php.conf.

Configuration file for reference:


     

    server

    {

    listen 80;

    #listen [::]:80;

    server_name local.swoole.com ;

    index index.html index.htm index.php default.html default.htm default.php;

    root /home/wwwroot/project/swoole;

    #include rewrite/none.conf;

    #error_page 404 /404.html;

    #include enable-php.conf;

    include enable-swoole-php.conf;

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$

    {

    expires 30d;

    }

    location ~ .*\.(js|css)? $

    {

    expires 12h;

    }

    location ~ /.well-known {

    allow all;

    }

    location ~ /\.

    {

    deny all;

    }

    access_log /home/wwwlogs/local.swoole.com.log;

    }

Copy the code

Currently, it is possible to edit the server segment directly.

2. Changes to the service code in the Controller folder take effect every time the service is restarted?

No, each restart of the service may affect the normal user use, normal processing of the request will be forced to close.

When running routing control code locally, try this command:


     

    ps aux | grep swoole_process_server_master | awk '{print $2}' | xargs kill -USR1

Copy the code

Send a USR1 signal to the master process. When Swoole Server receives this signal, it will let all workers restart after processing the current request.

To view all processes, try this command:


     

    ps -ef | grep 'swoole_process_server' | grep -v 'grep'

Copy the code

Need the source code in the article, follow the public number, reply “Swoole HTTP” can.

extension

  • You can try to upload files and make a small FTP server.

  • Learn the Swoole open source framework: EasySwoole, Swoft, One.

  • Swoole can be integrated into existing PHP frameworks.

Recommended reading

  • RPC in my eyes

  • Leadership: Situational Leadership

  • Explanation of the system – SSO single sign-on

This article is welcome to forward, forward please indicate the author and source, thank you!