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,搭建一个在线教育视频课程分享网站。
目录
相关文章
|
5月前
|
PHP Android开发
android通过http上传文件,服务器端用php写(原创)
android通过http上传文件,服务器端用php写(原创)
54 4
|
3月前
|
JSON Java Serverless
函数计算产品使用问题之如何使用Go SDK从HTTP上下文中提取JSON数据
函数计算产品作为一种事件驱动的全托管计算服务,让用户能够专注于业务逻辑的编写,而无需关心底层服务器的管理与运维。你可以有效地利用函数计算产品来支撑各类应用场景,从简单的数据处理到复杂的业务逻辑,实现快速、高效、低成本的云上部署与运维。以下是一些关于使用函数计算产品的合集和要点,帮助你更好地理解和应用这一服务。
|
3月前
|
网络协议 程序员 应用服务中间件
Swoole与Go系列教程之HTTP服务的应用
PHP 曾是Web开发领域佼佼者,随着业务壮大,异步和高并发方面不足显现。Swoole 曾经尝试填补空白,但局限性也比较的明显。Go 语言的崛起,简洁语法和并发优势吸引大厂使用,吸引了大多数程序员的转型。
997 0
Swoole与Go系列教程之HTTP服务的应用
|
4月前
|
PHP
php 获取带http或https的域名
php 获取带http或https的域名
144 4
|
4月前
|
JSON Serverless 对象存储
函数计算产品使用问题之如何创建一个同时具有HTTP触发器和OSS触发器的函数
函数计算产品作为一种事件驱动的全托管计算服务,让用户能够专注于业务逻辑的编写,而无需关心底层服务器的管理与运维。你可以有效地利用函数计算产品来支撑各类应用场景,从简单的数据处理到复杂的业务逻辑,实现快速、高效、低成本的云上部署与运维。以下是一些关于使用函数计算产品的合集和要点,帮助你更好地理解和应用这一服务。
|
4月前
|
网络协议 PHP
Swoole 源码分析之 Http Server 模块
想要了解到 `Http Server` 的全貌,其实只要把那张整体的实现图看懂就足以了。但是,如果想要有足够的深度,那么就还需要深入 `Swoole` 的源代码中,就着源码自行分析一遍。同时,也希望这一次的分析,能够给大家带来对 `Swoole` 更多的一些了解。并不要求要深刻的掌握,因为,很多的事情都不可能一蹴而就。从自己的实力出发,勿忘初心。
72 0
Swoole 源码分析之 Http Server 模块
|
5月前
|
消息中间件 网络协议 开发工具
MQ产品使用合集之rocketmq5.x只有tcp接入点吗,python sdk需要http接入点,请问怎么使用
消息队列(MQ)是一种用于异步通信和解耦的应用程序间消息传递的服务,广泛应用于分布式系统中。针对不同的MQ产品,如阿里云的RocketMQ、RabbitMQ等,它们在实现上述场景时可能会有不同的特性和优势,比如RocketMQ强调高吞吐量、低延迟和高可用性,适合大规模分布式系统;而RabbitMQ则以其灵活的路由规则和丰富的协议支持受到青睐。下面是一些常见的消息队列MQ产品的使用场景合集,这些场景涵盖了多种行业和业务需求。
170 2
|
5月前
|
安全 网络安全 开发工具
对象存储oss使用问题之flutter使用http库进行post请求文件上传返回400如何解决
《对象存储OSS操作报错合集》精选了用户在使用阿里云对象存储服务(OSS)过程中出现的各种常见及疑难报错情况,包括但不限于权限问题、上传下载异常、Bucket配置错误、网络连接问题、跨域资源共享(CORS)设定错误、数据一致性问题以及API调用失败等场景。为用户降低故障排查时间,确保OSS服务的稳定运行与高效利用。
215 1
|
5月前
|
监控 网络安全 PHP
对象存储oss使用问题之操作报错:Unable to execute HTTP request: SocketException如何解决
《对象存储OSS操作报错合集》精选了用户在使用阿里云对象存储服务(OSS)过程中出现的各种常见及疑难报错情况,包括但不限于权限问题、上传下载异常、Bucket配置错误、网络连接问题、跨域资源共享(CORS)设定错误、数据一致性问题以及API调用失败等场景。为用户降低故障排查时间,确保OSS服务的稳定运行与高效利用。
2378 0
|
5月前
|
JavaScript Java Serverless
函数计算中,这里是用的curl的方式,如何改用http的post方式请求?还有如何设置oss打包的zip的保存目录?
函数计算中,这里是用的curl的方式,如何改用http的post方式请求?还有如何设置oss打包的zip的保存目录?
193 0
下一篇
无影云桌面