Swoole based Simple HTTP Server Implementation using OSS PHP SDK

Alibaba Cloud
Jan 18, 2018 · 7 min read

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.

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.

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:

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.

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:

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.

Reference:

https://www.alibabacloud.com/blog/Swoole-based-Simple-HTTP-Server-Implementation-using-OSS-PHP-SDK_p347088?spm=a2c41.11157242.0.0

Alibaba Cloud

Written by

A global Cloud Computing and AI company, a subsidiary of Alibaba Group. Website: https://www.alibabacloud.com/

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade