Swoole based Simple HTTP Server Implementation using OSS PHP SDK

本文涉及的产品
对象存储 OSS,20GB 3个月
对象存储 OSS,内容安全 1000次 1年
对象存储 OSS,恶意文件检测 1000次 1年
简介: Currently, program developers are leveraging Swoole to implement network server programs in place of C++, Java and other complex programming languages.

0213_Android_DevOps_from_a_single_push_command_to_production

Introduction

Swoole, in the recent times, has taken over as the new "best language" in the coder's world.

As described officially, it is a high-performance network communication engine for PHP asynchronous and parallel requests. Its compilation purely utilizes the C language that provides PHP asynchronous multi-threaded server, asynchronous TCP/UDP network client, and asynchronous MySQL. Additionally, it uses asynchronous Redis, database connection pool, AsyncTask, message queue, millisecond timer, asynchronous file reads and writes, and asynchronous DNS query features. It is nested with HTTP/WebSocket server/ client and HTTP 2.0 server.

Swoole 2.0 supports a coroutine, such as Go language, to enable the use of fully synchronized code to implement an asynchronous program. The PHP code does not require additional keywords. Furthermore, the bottom layer automatically schedules the coroutine to implement asynchronous processing.

Advantages of Swoole

Let us examine its advantages.

●Purely C-compiled, with extremely powerful performance;
●Simple and easy to use, development-efficient;
●Event-driven, non-blocking asynchronous processing;
●Supporting millions of concurrent TCP connections;
●TCP/UDP/UnixSock;
●Server/client;
●Supporting asynchronous/synchronous/coroutine;
●Supporting multiprocessing/multi-threading;
●CPU affinity/daemon process;
●Supporting IPv4/IPv6 networks.

Application Scenario

To understand Swoole more comprehensively, let us look at a use-case for Swoole.

Currently, program developers are leveraging Swoole to implement network server programs in place of C++, Java and other complex programming languages. It has been in use by several mobile internet, Internet of Things, online games and mobile gaming organizations. The combination of PHP and Swoole can considerably improve development efficiency.

An officially provided PHP network framework extended and developed based on Swoole supports HTTP, FastCGI, WebSocket, FTP, SMTP, RPC and other network protocols.

Swoole users are everywhere, spread out across the United States, Britain, France, India and other countries. Several well-known internet companies in China such as Tencent, Baidu, Alibaba and YY Language also use this product.

Further, let us now delve into functioning with Swoole using OSS PHP SDK.

1. Install Swoole

As the first step, you need to install Swoole on your system. If you have PHP7 and PECL installed, you can use the following command directly.
pecl install swoole

Then locate the specific Loaded Configuration File using php -info | grep php.ini.
It may be different for different environments, in ours it is /etc/php/7.0/cli/php.ini.
Then, you need to run
vim /etc/php/7.0/cli/php.ini

Next, add
extension = "swoole.so"

Or you may compile and install Swoole in your system. However, you need to do this until you can see the text shown in the following screenshot.

1

2. Use OSS PHP SDK

For using Swoole in OSS PHP SDK, you need to ensure that the PHP SDK setup is successful and ready. The steps are as follows:

●git clone https://github.com/aliyun/aliyun-oss-php-sdk.git # Download the code from the OSS PHP SDK code address.
●Run cd aliyun-oss-php-sdk/.
●Configure samples/Config.php #.
●php sample/Swoole.php # Run a sample program
●Run curl 127.0.0.1:9503.
●"Hello Swoole" should display on your screen.

2

Once it displays, Swoole and OSS PHP SDK are ready for use, together.

3. Set Nginx for Reverse Proxy

After carrying out the steps mentioned above, you can access OSS through Swoole. However, the more common practice, on the server side, is to use nginx as a front-end proxy. Then access the initiated Swoole server through the nginx reverse proxy server.

Specific steps to carry it out are as below (You may skip these if you have already installed nginx.).

●Download the latest version from wget http://nginx.org/download/nginx-1.11.3.tar.gz
●Next, unzip the package using tar -zxvf nginx-1.11.3.tar.gz \
●Then enter the command cd nginx-1.11.3
●Now, configure the software through ./configure --prefix=/usr/local/nginx #
●Please make a note that the following error may occur at this step "pcre.h No such file or directory".
●You can find an=bout more about this error here.
●Further, you need to install libpcre3-dev with the command: sudo apt-get install libpcre3-dev
●sudo make install
●sudo /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
●Note: The "-c" specifies the path to the configuration file. If you do not add it, nginx will automatically load the configuration file at the default path. You can view the help command via "-h".
●ps -ef | grep nginx
●You can view the nginx progress here:

3

If you can see the above screenshot on your screen, it indicates that nginx is working normally.

Next, we will use nginx reverse proxy 127.0.0.1:9503 and modify /usr/local/nginx/conf/nginx.conf.

You can execute it as follows:

http {
    include       mime.types;
    default_type  application/octet-stream;
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
    #access_log  logs/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    #gzip  on;
        upstream swoole{
                server 127.0.0.1:9503;
                keepalive 4;
        }
    server {
        listen       80;
        server_name  www.swoole.com;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            proxy_pass http://swoole;
            proxy_set_header Connection "";
            proxy_http_version 1.1;
            root   html;
            index  index.html index.htm;
        }
        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}

●Now, you need to reload nginx to bring the configuration into effect with the command: sudo /usr/local/nginx/sbin/nginx -s reload.

●Next, add 127.0.0.1 www.swoole.com in vim /etc/hosts.

●To verify the result, you can use curl www.swoole.com or the browser to open the domain name and check whether "Hello Swoole" is displaying on your screen.

4. Experiences using Swoole

If "Hello Swoole" is the only result after following the steps until now, then you are missing something.

Let us move forward and see what could be missing? There is a sample.jpg file in the ./aliyun-oss-php-sdk directory for your reference and use. The sample code for uploading the file is as follows:

<?php
require_once __DIR__ . '/Common.php';

use OSS\OssClient;
use OSS\Core\OssException;

$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//*******************************Simple use***************************************************************
$options = array(
    OssClient::OSS_FILE_DOWNLOAD => "example_download.jpg",
);

$ossClient->uploadFile($bucket, "example.jpg", "example.jpg");
$ossClient->getObject($bucket, "example.jpg", $options);

You should check the result after executing the command.

4

The simplest file upload/download methods in OSS is as below.

Call the OSS PHP SDK in the Swoole server following the steps above. Then use the server as the nginx proxy. Next, the simplest OSS upload/download code will be changed as below. :

<?php
require_once __DIR__ . '/Common.php';

use OSS\OssClient;
use OSS\Core\OssException;

$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//*******************************Simple use***************************************************************

$options = array(
    OssClient::OSS_FILE_DOWNLOAD => "example_download.jpg",
);

$serv = new swoole_http_server("127.0.0.1", 9503);

$serv->set(array(
        'worker_num' => 16,
        'daemonize' => true,
        'max_request' => 10000,
        'dispatch_mode' => 2,
        'debug_mode'=> 1,
        'log_file' => '/tmp/swoole_http_server.log',
));

$serv->on('Request', function($request, $response) use($ossClient, $bucket, $options){

        $ossClient->uploadFile($bucket, "example.jpg", "example.jpg");
        $ossClient->getObject($bucket, "example.jpg", $options);

        $response->end("Hello Swoole\n");
});

$serv->start();

●php sample/Swoole.php
●Now, you need to run the command: curl www.swoole.com.

Do you receive no response for a long time and nginx reports an error?
Check the nginx access log and you will find the 504 error. Open the swoole_http_server.log that we set in Swoole and you will find the following on your screen:

5

The two problems that you may face are:

●Problem 1: The error indicates that OSS PHP SDK failed to find this example.jpg file. However, example.jpg is a local file. Why can't OSS PHP SDK find it?
●Problem 2: Even if this error is true, why did it cause nginx to report the 504 error?

Now, you may be wondering, how can you solve these two problems?

Problem 1 could arise from a bug of Swoole. An actual test showed that Swoole calculates the relative path from the root directory "/", rather than the current directory. You can then write a resolution path for the file.

For Problem 2, Swoole users must encapsulate the error thrown by the called interface. That means that the error thrown by OSS PHP SDK in the case of this article is to allow nginx to identify it correctly.

Conclusion

The event-based network layer in Swoole takes advantage of the underlying epoll/kqueue implementation to cater to several thousand connections. After a request, the allocated memory does not free itself as it does in legacy apache/php-fpm, improving its performance significantly. You can create enhanced web applications with more control, real-time chatting servers, and much more with Swoole.

相关实践学习
借助OSS搭建在线教育视频课程分享网站
本教程介绍如何基于云服务器ECS和对象存储OSS,搭建一个在线教育视频课程分享网站。
目录
相关文章
|
8月前
|
PHP Android开发
android通过http上传文件,服务器端用php写(原创)
android通过http上传文件,服务器端用php写(原创)
77 4
|
3月前
|
存储 人工智能 开发工具
AI助理化繁为简,速取代码参数——使用python SDK 处理OSS存储的图片
只需要通过向AI助理提问的方式输入您的需求,即可瞬间获得核心流程代码及参数,缩短学习路径、提升开发效率。
1466 4
AI助理化繁为简,速取代码参数——使用python SDK 处理OSS存储的图片
|
7月前
|
前端开发 网络协议 测试技术
探索PHP的异步编程模型:从React到Swoole
在Web开发领域,PHP一直以简单易用著称。然而,随着互联网应用对性能和并发处理能力的不断追求,传统的同步阻塞式编程模型已逐渐暴露出局限性。本文将深入探讨PHP中的异步编程模型,从早期的React到现代的Swoole,分析其原理、优势及应用场景,并通过实例展示如何利用这些工具提升PHP应用的性能和响应速度。文章旨在为PHP开发者提供一种全新的视角,帮助他们在构建高性能Web应用时做出更合理的技术选择。
88 0
|
4月前
|
缓存 程序员 PHP
为什么说 Swoole 是 PHP 程序员技术水平的分水岭?
【9月更文挑战第8天】Swoole 被视为 PHP 程序员技术水平的分水岭,因为它要求程序员深入理解底层原理(如网络编程、异步和并发模型),具备性能优化能力(如高效服务器开发、数据库连接池管理),拥有架构设计能力(如微服务架构、项目复杂度管理),并具备持续学习和自我提升意识。熟练掌握 Swoole 的程序员在技术能力和综合素质方面更具优势。
|
4月前
|
缓存 网络协议 程序员
为什么说 Swoole 是 PHP 程序员技术水平的分水岭?
【9月更文挑战第7天】Swoole 因其异步非阻塞编程模式、高性能服务器开发能力、性能优化工具及拓展技术视野等特点,被视为 PHP 程序员技术水平的分水岭。它要求程序员掌握异步编程、协程、网络协议等知识,并具备性能优化和系统管理能力,从而全面提升技术水平。
|
5月前
|
JavaScript 应用服务中间件 Go
PHP的异步编程:探索Swoole的奥秘
在传统的同步编程模型中,PHP的表现一直受到诟病。然而,随着Swoole的出现,PHP开发者得以迈入异步编程的新纪元。本文将深入浅出地介绍Swoole如何让PHP在性能和并发处理上实现飞跃,同时保持代码的简洁与优雅。
|
6月前
|
消息中间件 分布式计算 DataWorks
DataWorks产品使用合集之如何使用Python和阿里云SDK读取OSS中的文件
DataWorks作为一站式的数据开发与治理平台,提供了从数据采集、清洗、开发、调度、服务化、质量监控到安全管理的全套解决方案,帮助企业构建高效、规范、安全的大数据处理体系。以下是对DataWorks产品使用合集的概述,涵盖数据处理的各个环节。
|
7月前
|
PHP
php 获取带http或https的域名
php 获取带http或https的域名
187 4
|
6月前
|
JSON Java Serverless
函数计算产品使用问题之如何使用Go SDK从HTTP上下文中提取JSON数据
函数计算产品作为一种事件驱动的全托管计算服务,让用户能够专注于业务逻辑的编写,而无需关心底层服务器的管理与运维。你可以有效地利用函数计算产品来支撑各类应用场景,从简单的数据处理到复杂的业务逻辑,实现快速、高效、低成本的云上部署与运维。以下是一些关于使用函数计算产品的合集和要点,帮助你更好地理解和应用这一服务。
|
7月前
|
JSON Serverless 对象存储
函数计算产品使用问题之如何创建一个同时具有HTTP触发器和OSS触发器的函数
函数计算产品作为一种事件驱动的全托管计算服务,让用户能够专注于业务逻辑的编写,而无需关心底层服务器的管理与运维。你可以有效地利用函数计算产品来支撑各类应用场景,从简单的数据处理到复杂的业务逻辑,实现快速、高效、低成本的云上部署与运维。以下是一些关于使用函数计算产品的合集和要点,帮助你更好地理解和应用这一服务。