Table of Contents
小结" >小结
扩展" >扩展
Home PHP Framework Swoole Introducing the application of Swoole HTTP

Introducing the application of Swoole HTTP

Jan 13, 2021 am 10:07 AM
http swoole

Introducing the application of Swoole HTTP

推荐(免费):Swoole

概述

我们都知道HTTP是一种协议,允许WEB服务器和浏览器通过互联网进行发送和接受数据。

想对HTTP进行详细的了解,可以找下其他文章,这篇文章不多做介绍。

我们在网上能看到的界面,图片,动画,音频,视频等,都有依赖这个协议的。

在做WEB系统的时候,都使用过IIS,Apache,Nginx吧,我们利用Swoole也可以简单的实现一个WEB服务器。

主要使用了HTTP的两个大对象:Request请求对象,Response响应对象。

请求,包括GET,POST,COOKIE,Header等。

响应,包括状态,响应体,扩展,发送文件等。

不多说,先分享两个程序:

  • 一,实现一个基础的Demo:“你好,Swoole。”

  • 二,实现一个简单的路由控制

本地版本:  

  • PHP 7.2.6

  • 旋风4.3.1

代码

一,Demo:“你好,Swoole。”   

示例效果:    

     

备注:IP地址是我的虚拟机。   

示例代码:   

<?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, //开启2个worker进程
 'max_request' => 4, //每个worker进程 max_request设置为4次
 'daemonize' => false, //守护进程(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;
        echo "SWOOLE ".SWOOLE_VERSION . " 服务已启动".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 after login

二,路由控制     

示例效果:    

目录结构:

├─ swoole_http  -- 代码根目录
│ ├─ server.php
│ ├─ controller
│ ├── Index.php
│ ├── Login.php
Copy after login

示例代码:     

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, //开启2个worker进程
 'max_request' => 4, //每个worker进程 max_request设置为4次
 'document_root' => '',
 'enable_static_handler' => true,
 'daemonize' => false, //守护进程(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');

        echo "SWOOLE ".SWOOLE_VERSION . " 服务已启动".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不存在');
 }

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

            $count_path_info = count($path_info);
 if ($count_path_info > 4) {
                $response->status(404);
                $response->end('URL不存在');
 }

            $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 不存在";

 if (class_exists($controller)) {
            $class = new $controller();
            $result = "method 不存在";
 if (method_exists($controller, $method)) {
                $result = $class->$method($request);
 }
 }

        $response->end($result);
 }
}

$server = new Server();
Copy after login

Index.php

<?php

class Index
{
 public function home($request)
 {
        $get = isset($request->get) ? $request->get : [];

 //@TODO 业务代码

        $result = "<h1>你好,Swoole。</h1>";
        $result.= "GET参数:".json_encode($get);
 return $result;
 }
}
Copy after login

Login.php

<?php

class Login
{
 public function index($request)
 {
        $post = isset($request->post) ? $request->post : [];

 //@TODO 业务代码

 return "<h1>登录成功。</h1>";
 }
}
Copy after login

小结

一,Swoole可以替代Nginx吗?

暂时不能,通过Swoole越来越强大,以后说不准。

官方建议Swoole与Nginx结合使用。

Http \ Server对Http协议的支持并不完整,建议仅作为应用服务器。并且在前端增加Nginx作为代理。

根据自己的Nginx配置文件,可以自行调整。

例如:可以添加一个配置文件

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 after login

我们都习惯于将虚拟域名的配置文件放在vhost文件夹中。

例如,虚拟域名的配置文件为:local.swoole.com.conf,可以选择加载enable-php.conf,也可以选择加载enable-swoole-php.conf。

配置文件供参考:

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 after login

当前,我们直接编辑server段的代码也是可以的。

二,修改了controller文件夹中的业务代码,每次都是重启服务才生效吗?

不是,每次重启服务可能会影响到正常用户使用的,正常处理的请求会被强制关闭。

在本地运行路由控制的代码时,试试这个命令:

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

给master进程发送一个USR1的信号,当Swoole Server接收到该信号后,就会让所有worker在处理完当前的请求后,进行重启。

如果查看所有的进程,试试这个命令:

ps -ef | grep 'swoole_process_server'| grep -v 'grep'
Copy after login

扩展

  • 可以试着上传文件,做一个小的FTP服务器。

  • 可以学习Swoole开源框架:EasySwoole,Swoft,One。

  • 可以将Swoole整合到当前正在使用的PHP框架中。

更多相关精品文章敬请关注swoole框架栏目!    

The above is the detailed content of Introducing the application of Swoole HTTP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use swoole coroutine in laravel How to use swoole coroutine in laravel Apr 09, 2024 pm 06:48 PM

Using Swoole coroutines in Laravel can process a large number of requests concurrently. The advantages include: Concurrent processing: allows multiple requests to be processed at the same time. High performance: Based on the Linux epoll event mechanism, it processes requests efficiently. Low resource consumption: requires fewer server resources. Easy to integrate: Seamless integration with Laravel framework, simple to use.

Understand common application scenarios of web page redirection and understand the HTTP 301 status code Understand common application scenarios of web page redirection and understand the HTTP 301 status code Feb 18, 2024 pm 08:41 PM

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

Which one is better, swoole or workerman? Which one is better, swoole or workerman? Apr 09, 2024 pm 07:00 PM

Swoole and Workerman are both high-performance PHP server frameworks. Known for its asynchronous processing, excellent performance, and scalability, Swoole is suitable for projects that need to handle a large number of concurrent requests and high throughput. Workerman offers the flexibility of both asynchronous and synchronous modes, with an intuitive API that is better suited for ease of use and projects that handle lower concurrency volumes.

How does swoole_process allow users to switch? How does swoole_process allow users to switch? Apr 09, 2024 pm 06:21 PM

Swoole Process allows users to switch. The specific steps are: create a process; set the process user; start the process.

How to restart the service in swoole framework How to restart the service in swoole framework Apr 09, 2024 pm 06:15 PM

To restart the Swoole service, follow these steps: Check the service status and get the PID. Use "kill -15 PID" to stop the service. Restart the service using the same command that was used to start the service.

Which one has better performance, swoole or java? Which one has better performance, swoole or java? Apr 09, 2024 pm 07:03 PM

Performance comparison: Throughput: Swoole has higher throughput thanks to its coroutine mechanism. Latency: Swoole's coroutine context switching has lower overhead and smaller latency. Memory consumption: Swoole's coroutines occupy less memory. Ease of use: Swoole provides an easier-to-use concurrent programming API.

HTTP 200 OK: Understand the meaning and purpose of a successful response HTTP 200 OK: Understand the meaning and purpose of a successful response Dec 26, 2023 am 10:25 AM

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

http request 415 error solution http request 415 error solution Nov 14, 2023 am 10:49 AM

Solution: 1. Check the Content-Type in the request header; 2. Check the data format in the request body; 3. Use the appropriate encoding format; 4. Use the appropriate request method; 5. Check the server-side support.

See all articles