Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

Table of Contents

Introduction 1.1

Prologue 1.2

1 Environment to build 1.3

1.1 Environment to build 1.4

1.2 Set up Echo server 1.5

2 Acquaintance Swoole 1.6

2.1 Worker process 1.7

2.2 TaskWorker process 1.8

2.3 Timer Timer 1.9

2.4 Process process 1.10

2.5 Table Memory table 1.11

2.6 Multi-port listening 1.12

2.7 sendfile File Support 1.13

2.8 SSL stand by 1.14

3 Swoole protocol 1.15

3.1 EOF protocol 1.16

3.2 Baotou fixed agreement 1.17

3.3 Http protocol 1.18

3.4 WebSocket protocol 1.19

3.5 MTQQ protocol 1.20

4 Swoole Client 1.21

4.1 Client 1.22

4.2 asynchronous Http Client 1.23

4.3 asynchronous WebSocket Client 1.24

4.4 asynchronous MySQL Client 1.25

4.5 asynchronous Redis Client 1.26

5 Swoole asynchronous IO 1.27

5.1 AsyncIO 1.28

5.2 EventLoop 6 1.29

Swoole use 1.30

1
7 Application Framework 1.31

7.1 ZPHP 1.32

7.2 TSF 1.33

7.3 Hprose 1.34

7.4 Dora-rpc 8 Existing 1.35

framework support 1.36

8.1 Yaf 1.37

8.2 Phalcon 1.38

8.3 Thinkphp 9 Project 1.39

combat configuration 1.40

options * Appendix 1.41

Appendix Appendix * * 1.42

callback list of attributes 1.43

Appendix * List of functions 1.44

2
Introduction

Concise Guide to Swoole Author

Lancelot (Li Danyang ID: Meow will knock code) from LinkedDestiny Studio (Pull machine chamber)

Company : Bilibili

Description

A concise guide to php swoole extension.

Contact

simonarthur2012@gmail.com (Lancelot)

Notice

I'm sorry that I can not translate my book to English. If someone wants to help me, Please send an email to me, thanks

3
Prologue

EDITORIAL words

The default book reader has the following capabilities:

Skilled use PHP Skilled use of language MySQL , Redis Familiar with database Linux Basic understanding of the

operating system Unix Network programming knowledge (see " Unix Network Programming (Volume 1 )") basic gdb use

The first chapter will explain how to configure PHP & Swoole Development environment, will be a step by step installation depends listed and the desired command.

The second chapter will explain Swoole The basic features and configuration options, including Worker process, Task Worker process, Timer Timer, Process process,

swoole_table Memory tables, etc., will explain the basics of using these features.

The third chapter will explain Swoole Built-in part of the agreement, explain how to customize TCP The application-layer communications protocol. It will also

introduce Swoole Built-in multi-protocol analytical methods, such as Http server, WebSocket Server and so on.

The fourth chapter will explain Swoole Client Relevant content, explain how to create and use Swoole Provide a variety of Client ,Such as

TCP Client ,asynchronous Http Client ,asynchronous MySQL Client Wait.

The fifth chapter will explain Swoole Asynchronous IO Section, including asynchronous read and write files and asynchronous EventLoop Event loop.

The sixth chapter will explain Swoole Some practical usage, such as the use Task Process asynchronous task processing, use Process

Perform monitoring commands

Chapter 7 explains Swoole Some of the relevant frameworks, such as ZPHP , Hprose , Dora-rpc and many more

Chapter 8 explains Swoole Some combined with existing frameworks, such as Swoole-Yaf , Swoole-Phalcon Wait

Chapter IX began to explain Swoole Combat, through a number of practical projects to understand Swoole Applications. (The concept)

4
1 Environment to build

Environment to build Environment Setup

This chapter describes in detail how to build Swoole Development environment, including PHP installation, Swoole Installation,

expansion-related installation and so on. This Chapter will introduce how to set up the development environment of Swoole, including the

installation of PHP, Swoole extension and other related extensions. In this chapter, you can learn how to quickly build a complete set of Swoole

Development environment. Going through this chapter, we can learn how to quick set up a complete Swoole development environment.

related software Essentials

category Type name Name version Version

OS ( Linux ) Ubuntu 16.04

OS ( Mac ) OSX 10.11

Language Server Script PHP 5.6.22

Spread Extension Swoole 1.8.5-stable

Spread Extension Redis 3.0.0

database Database MySQL 5.7.12

database Database Redis 3.0.7

Relevant framework Related Frameworks

category Type name Name version Version

MVC ZPHP Master Branch Branch

MVC Yaf Master Branch Branch

RPC Hprose Master Branch Branch

PRC Dora-RPC Master Branch Branch

DB Model ThinkPHP 3.2.2 ( Use only Model Module Only Model Used)

5
1.1 Environment to build

Environment to build Environment Setup Linux Installation

environment Setup for Linux

Compiler Environment Compiling Environment PHP installation

PHP Installation Mac Installation environment Setup for Mac

installation OpenSSL OpenSSL Installation

installation Curl Curl Installation

installation PHP PHP Installation Swoole Extended

installation Swoole Installation

Environment to build Environment Setup

[TOC]

Linux Installation environment Setup for Linux

Linux The operating system usually has its own package management software ( Ubuntu of apt-get , CentOS of yum , Mac OSX of

HomeBrew Etc.), and therefore generally can be installed directly by the package management software PHP . But this installation

PHP It is not suitable for running Swoole Therefore this chapter describes how to install via source code compilation. Linux has usually

got its own package management tools (like apt-get for Ubuntu, yum for CentOS, HomeBrew for Mac OSX ...). So for most of the

cases, we can directly install php using those tools. But for Swoole, compiling the source codes to install is suggested.

Compiler Environment Compiling Environment

I want to compile and install PHP We first need to install the corresponding compilation tools. Ubuntu Use the following command to install

dependencies and compilation tools: To successfully compile PHP, we have to get our compilers and other related tools ready We can install

compiling tools and dependencies by using commands.:

6
1.1 Environment to build

sudo apt-get install \ build-essential \ gcc

\ g ++ \

autoconf \

libiconv-hook-dev \ libmcrypt-dev \

libxml2-dev \

libmysqlclient-dev \ libcurl4-openssl-dev

\ libjpeg8-dev \ libpng12-dev \

libfreetype6-dev \

PHP installation PHP Installation

PHP download link Download Here you can choose the version you want to use. After the download source, extract to any local directory (read and write

permissions guarantee). Download PHP of the version you want. Once done with that, extract it to any R / W directory.

Use the following command to compile and install PHP : Use following commands to compile and install PHP:

7
1.1 Environment to build

cd php-5.6.22 /

. / Configure --prefix = / usr / local / php \

- - with-config-file-path = / etc / php \

- - enable-fpm \

- - enable-pcntl \

- - enable-mysqlnd \

- - enable-opcache \

- - enable-sockets \

- - enable-sysvmsg \

- - enable-sysvsem \

- - enable-sysvshm \

- - enable-shmop \

- - enable-zip \

- - enable-soap \

- - enable-xml \

- - enable-mbstring \

- - disable-rpath \

- - disable-debug \

- - disable-fileinfo \

- - with-mysql = mysqlnd \

- - with-mysqli = mysqlnd \

- - with-pdo-mysql = mysqlnd \

- - with-pcre-regex \

- - with-iconv \

- - with-zlib \

- - with-mcrypt \

- - with-gd \

- - with-openssl \

- - with-mhash \

- - with-xmlrpc \

- - with-curl \

- - with-imap-ssl

sudo make

sudo make install sudo mkdir / etc /

php

sudo cp php.ini-development /etc/php/php.ini

Note that the above PHP Compiler option to adjust according to the actual situation. To be sure, any of these compiling options is adjustable

according to your specific needs.

In addition, we also need to PHP Executable directory to the environment variable. use Vim / Sublime Open ~ /. bashrc , Add the

following to the end: Also, we need to add PHP's bin directory to environment variables Open file '~ / .bashrc' by Vim / Sublime And

add following contents to the end of the file..:

export PATH = / usr / local / php / bin: $ PATH export PATH = / usr /

local / php / sbin: $ PATH

Once saved, the terminal enter the command: Having saved that, run following commands in Terminal:

8
1.1 Environment to build

source ~ / .bashrc

By this time you can php --version View php version. Right now, you can check out the PHP version using php --version!

Mac Installation environment Setup for Mac

Mac system build-in PHP ,but Mac For the OpenSSL Related functions do some limitations, the use of a Secure Transport To replace OpenSSL .

Therefore, it is recommended to re-compile and install PHP surroundings. MacOS comes with a certain version of PHP. But OpenSSL for

that version is restricted and got replaced by

Secure Transport. For that matter, reinstalling it in a code compiling way is still highly recommanded.

installation OpenSSL OpenSSL Installation

Mac genuine 0.9.8 Version of OpenSSL Some time will be used Warning Anyway, I could not understand ...... The OpenSSL that

comes with MacOS, while using, will produce some warnings. And why is that? Kill me to know ... Installation command: Installation

Commands:

brew install openssl

After installation, you need to link the new openssl The environment variable. After that, we will need to link the new OpenSSL into

environment variables.

brew link --force openssl

installation Curl Curl Installation

Mac The original system Curl Use the default Secure Transport Led by option Certificate function sets all invalid. Decisive

reinstallation. The Curl that comes with MacOS uses Secure Transport by default. That causes the invalid of all the

certificates set by function 'option'. So reinstallation is a must.

brew install curl --with-openssl && brew link curl --force

9
1.1 Environment to build

installation PHP PHP Installation

PHP The official website to download a version of PHP (I chose 5.6.22 ), Use the following command to compile and install. . Download a

version of PHP from PHP.net (for my case, it's 5.6.22) Compile source codes to install by using following commands:

cd / path / to / php /

. / Configure

- - prefix = / usr / local / php

- - with-config-file-path = / etc / php

- - with-openssl = / usr / local / Cellar / openssl / 1.0.2g /

- - with-curl = / usr / local / Cellar / curl / 7.48.0 /

make && make install

Here I list only two options require special settings with-openssl with with-curl . Here I filled up two specific options with-openssl and with-curl.

After installation is complete, the following command: After installation, run following commands:

sudo cp / usr / local / php / bin / php / usr / bin / sudo cp / usr / local / php / bin / phar *

/ usr / bin / sudo cp / usr / local / php / bin / php-config / usr / bin / sudo cp / usr / local /

php / bin / phpize / usr / bin /

Then, set up php.ini Then, we can configure php.ini:

sudo mkdir / etc / php

sudo cp php.ini.development /etc/php/php.ini

Swoole Extended installation Swoole Installation

Swoole Extended Download Download Extract the source to any directory, execute the following command: Extact the codes to any directory and

run following commands:

cd swoole-src-swoole-1.7.6-stable / phpize

. / Configure sudo

make

sudo make install

10
1.1 Environment to build

swoole of./ configure There are many additional parameters, you can ./ configure --help View command, select the default items are

here) swoole's './configure' has got many optinal configurations. Check them out by using './configure --help'. Here we are just

going to leave them default.

After installation is complete, enter / etc / php Directory, open php.ini File, which add the following sentence: Having finished all that, go to

the path '/ etc / php' and edit php.ini Add the following line to the file.:

extension = swoole.so

Then enter the command in the terminal php -m View the extended installation. If you see listed in the extended swoole , Then the installation was

successful. All Done! Use php -m to list all the extensions and see if swoole is around.

11
1.2 Set up Echo server

Set up Echo server Start With An Echo Server!

[TOC]

How to explain all network communications programming books will be the first to write an explanation Echo Server, this book is no

exception. This chapter explains how to quickly write based on Swoole expanded Echo server. Almost all network programming books start

with teaching how to build an Echo Server. Well, we will do the same for this guide. In this chapter, we will learn how to quickly build an

Echo Server based on Swoole!

Server Server

Create Server.php File and enter the following: Create a file named 'Server.php' and type in following codes:

12
1.2 Set up Echo server

// Server

class Server

private $ Serv;

public function __construct () {

$ This-> serv = new swoole_server ( "0.0.0.0" , 9501 ); $ This-> serv-> set ( array (

'Worker_num' => 8 ,

'Daemonize' => false ,

) );

$ This-> serv-> on ( 'Start' , array ($ This, 'OnStart' )); $ This-> serv-> on ( 'Connect' , array ($ This, 'OnConnect'

)); $ This-> serv-> on ( 'Receive' , array ($ This, 'OnReceive' )); $ This-> serv-> on ( 'Close' , array ($

This, 'OnClose' ));

$ This-> serv-> start ();}

public function onStart ($ Serv) {

echo "Start \ n" ;}

public function onConnect ($ Serv, $ fd, $ from_id) {

$ Serv-> send ($ fd, "Hello {$ fd}!" );

public function onReceive (Swoole_server $ serv, $ fd, $ from_id, $ data) {

echo "Get Message From Client {$ fd}: {$ data} \ n" ; $ Serv-> send ($ fd, $ data);}

public function onClose ($ Serv, $ fd, $ from_id) {

echo "Client {$ fd} close connection \ n" ;}}

// Start the server Start the server

$ Server = new Server ();

Client Client

Create Client.php File and enter the following: Create a file named 'Client.php' and type in following codes:

13
1.2 Set up Echo server

<? Php

class Client

private $ Client;

public function __construct () {

$ This-> client = new swoole_client (SWOOLE_SOCK_TCP);}

public function connect () {

if (! $ This-> client-> connect ( "127.0.0.1" , 9501 , 1 )) {

echo "Error: {$ this-> client-> errMsg} [{$ this-> client-> errCode}] \ n" ;}

fwrite (STDOUT, " Please enter a message Please input msg : " );

$ Msg = trim (fgets (STDIN)); $ this-> client-> send

($ msg);

$ Message = $ this-> client-> recv ();

echo "Get Message From Server: {$ message} \ n" ;}}

$ Client = new Client (); $ client-> connect

();

run Run it!

in Terminal Under Run php Server.php You can start the server in another Terminal Under execution php Client.php , Enter the content to be

transmitted, the server can send messages to and receive messages from the server. To start the Echo Server? Simply run

command 'php Server.php' in Terminal. Then run command 'php Client.php' in another Terminal window and input whatever you

want to send. Aha! See what's coming up in your Server's Terminal? Your messages are sent from the Client to the Server.

14
2 Acquaintance Swoole

15
2.1 Worker process

Worker process

Swoole Process Model

Worker Process Description

Worker Process life cycle

Swoole Process Model

First, we need to know about Swoole The process model. Swoole Is a framework for multi-process mode (can be analog

Nginx The process model), when a start Swoole When applied, it will create a total of 2 + n + m A process in which n for

Worker Number of processes, m for TaskWorker Number of processes, 2 As a Master And a process Manager Process, the relationship between them as shown in FIG.

among them, Master Process-based process, which creates Manager process, Reactor Threading Work / thread.

Reactor Thread actually running epoll Examples for accept Client connection and receiving client data;

Manager Process for the management process, the role of this process is to create, manage all Worker Process and TaskWorker

process.

Worker Process Description

Worker As the process Swoole Work processes, all of the business logic code are running on this process. when Reactor After the thread has received data from

the client, the data will be transmitted to the packing by a conduit Worker Process (see data distribution method dispatch_mode ).

16
2.1 Worker process

Worker Process life cycle

One Worker Life-cycle process as shown:

When a Worker After the process is successfully created, will call onWorkerStart Callback, then enter the event loop waiting for data. When the data is received by

the callback function, start processing data. If a critical error occurs during the processing of data lead to withdraw from the process, or Worker The total

number of requests processed process reaches the specified upper limit, Worker Process calls onWorkerStop Callback and end of the process.

17
2.2 TaskWorker process

Task Worker

Profile

Examples

Brief introduction

Task Worker Yes Swoole In a special work process, the role of the process is time-consuming to deal with some tasks in order to achieve release Worker The

purpose of the process. Worker Process by swoole_server Objects task The method of delivery of a task to Task Worker process.

Worker Process through Unix Sock It sends the data to the pipe Task Worker ,such Worker The process can continue to process the new logic, without waiting for

time-consuming tasks. It should be noted that, due to Task Worker Is an independent process, and therefore can not share global variables directly between the

two processes is required Redis , MySQL or swoole_table To achieve inter-process shared data.

Examples

need to use Task Worker It requires some necessary operations.

First, we need to set swoole_server The configuration parameters:

$ Serv-> set ( array (

'Task_worker_num' => 2 , // Set to start 2 More task process

) );

Then, the necessary binding callback function:

$ Serv-> on ( 'Task' , 'OnTask' ); $ Serv-> on ( 'Finish' , 'OnFinish'

);

Wherein two callback prototype is as follows:

18
2.2 TaskWorker process

/ **

* @param $ serv swoole_server swoole_server Objects

* @param $ task_id int task id

* @param $ from_id int Delivery task worker_id

* @param $ data string Delivery of data

*/

function onTask (Swoole_server $ serv, $ task_id, $ from_id, $ data) ;

/ **

* @param $ serv swoole_server swoole_server Objects

* @param $ task_id int task id

* @param $ data string Task returns data

*/

function onFinish (Swoole_server $ serv, $ task_id, $ data) ;

In practice logic, when it is necessary to initiate a task request, you can invoke a method:

$ Data = "Task data" ; $ Serv-> task ($ data, -1 ); // -1 Representatives do not specify task process

// in 1.8.6+ Version, you can dynamically specify onFinish function

$ Serv-> task ($ data, -1 , function (Swoole_server $ serv, $ task_id, $ data) {

echo "Task Finish Callback \ n" ;});

19
2.3 Timer Timer

Timer Timer

Timer principle

Timer Timer is Swoole Extended a millisecond timer provided, whose role is to perform a specified callback function after every specified time interval, to

achieve a scheduled task functions. The new version of Swoole , The timer is based on epoll

Method timeout Mechanism implemented, the timing is no longer dependent on a separate thread, higher accuracy. Simultaneously, Swoole The minimum heap

memory expansion using a timer, the timer reduce the number of retrieval, improved operating efficiency.

Use timers

in Swoole Function prototype, the timer is as follows:

// function onTimer (int $ timer_id, mixed $ params = null); // Prototype for the callback

int swoole_timer_tick (int $ ms, mixed $ callback, mixed $ param = null ); Int swoole_server :: tick (int $ ms, mixed $ callback, mixed

$ param = null );

// function onTimer (); // Prototype for the callback (does not accept any parameters)

void swoole_timer_after (int $ after_time_ms, mixed $ callback_function); void swoole_server :: after (int $ after_time_ms, mixed $

callback_function);

tick Timer is a timer permanently, use tick After the implementation of a method to create the timer will run every specified number of milliseconds callback function.

In the creation of the timer, you can tick The third function parameters, to pass some custom parameters callback Callback function. Alternatively, you can use PHP

The closure ( use Keywords) to achieve mass participation. Specific examples are as follows:

$ Str = "Say" ;

$ Timer_id = swoole_timer_tick ( 1000 , function ($ Timer_id, $ params) use ($ Str) {

echo . $ Str $ params; // Export "Say Hello"

}, "Hello" );

tick Function returns the timer id . When we no longer need a timer, according to the id ,transfer swoole_timer_clear Function to delete the

timer. It should be noted that the timer is not created cross-process, therefore, in a Worker Process created a timer, only in this Worker

Delete the process, we must pay attention to (use $ worker_id Variable to distinguish Worker process);

20
2.3 Timer Timer

after Timer is a temporary timer. use after Ways to create timers performed only once after the specified number of milliseconds

callback Function, the timer will be deleted after execution is complete. after Timer callback function takes no arguments, parameters can be passed by way of

closure and to be transmitted by way of the class member variable. Specific examples are as follows:

class Test

private $ Str = "Say Hello" ;

public function onAfter ()

echo $ This-> str; // Export "Say Hello"

}}

$ Test = new Test (); swoole_timer_after ( 1000 , array ($ Test, "OnAfter" ); // Member variables

swoole_timer_after ( 2000 , function () use ($ Test) { // Closure

$ Test-> onAfter (); // Export "Say Hello"

});

twenty one
2.4 Process process

twenty two
2.5 Table Memory table

twenty three
2.6 Multi-port listening

Multi-port listening

Multi-port listening

In practical application scenario, the server may require a different monitor host Different ports under. For example, an application server, you may need to listen to

the service port outside the network, but also need to manage the ports in the listening network. in Swoole You can easily achieve this function. Swoole provided addlistener

Function is used to add a server needs to listen host and

port And specify the corresponding Socket Types of( TCP , UDP , Unix Socket And the corresponding IPv4 with IPv6 version). code show as below:

$ Serv = new swoole_server ( "192.168.1.1" , 9501 ); // Listening outside the network 9501 port

$ Serv-> addlistener ( "127.0.0.1" , 9502 , SWOOLE_TCP); // Monitor local 9502 port

$ Serv-> start (); // addlistener gotta be start Before calling

at this time, swoole_server It will simultaneously monitor two host Two ports under. It should be noted here that the data from the two ports will be the

same onReceive Callback function to get, then we should use swoole Another member function

connection_info , To get through this function fd of from_port , You can determine the type of message.

$ Info = $ serv-> connection_info ($ fd, $ from_id);

// Come from 9502 Within the network management port

if ($ Info [ 'From_port' ] == 9502 ) {$ Serv-> send ($ fd, "Welcome admin \ n" );

// From outside the network

else {

$ Serv-> send ($ fd, 'Swoole:' . $ Data);

Multi-port hybrid protocol answer

You can see by the above examples, using the above method of multi-port monitor has many limitations: a single agreement, the callback function can not be

distinguished and so on. In practice, we often want to be able to simultaneously monitor two service ports and two ports using different protocols, such as the

use of a port RPC Agreement to provide services, to provide another port Http Agreement for Web Management page. therefore, Swoole From 1.8.0 Version began

offering a new set of multi-port listening mode. in

1.8.0 Future versions, Server Can monitor a plurality of ports, each port can be set to different treatment protocols ( set)

And callback functions ( on) Starts listening to the new port code is as follows:

twenty four
2.6 Multi-port listening

$ Port1 = $ server-> listen ( "127.0.0.1" , 9501 , SWOOLE_SOCK_TCP); $ port2 = $ server-> listen ( "127.0.0.1" , 9502 ,

SWOOLE_SOCK_UDP); $ port3 = $ server-> listen ( "127.0.0.1" , 9503 , SWOOLE_SOCK_TCP | SWOOLE_SSL);

We can see the newly added listening port can set a variety of attributes, listening IP ,The port number, TCP or UDP ,Do you need SSL encryption. In addition,

each of the newly established Port Objects can also set configuration options are as follows:

$ Port1-> set ( // Open fixed header agreement

'Open_length_check' => true ,

'Package_length_type' => 'N' ,

'Package_length_offset' => 0 ,

'Package_max_length' => 800 000 ,

);

$ Port3-> set ( // Open EOF Protocols and set SSL file

'Open_eof_split' => true ,

'Package_eof' => "\ R \ n" ,

'Ssl_cert_file' => 'Ssl.cert' ,

'Ssl_key_file' => 'Ssl.key' ,

);

In addition to different protocols, each Port You can also set their own unique callback function, thereby avoiding the problem of the determination of the source of

data for the same callback function.

$ Port1-> on ( 'Receive' , function ($ Serv, $ fd, $ from_id, $ data) {

$ Serv-> send ($ fd, 'Swoole:' . $ Data); $ serv-> close ($ fd);});

$ Port3-> on ( 'Receive' , function ($ Serv, $ fd, $ from_id, $ data) {

echo "Hello {$ fd}: {$ data} \ n" ;});

Precautions

Protocol processing option is not set the listening port, the default mode is not set to use

no-protocol callbacks listening port, use $ server Callback objects return an object of type

listening port swoole_server_port

The callback function different listening port, still the same Worker The implementation of the primary server within the process space WebSocket or Http Agreement,

the new monitor TCP The default will inherit the main port Server The protocol settings. It must be called separately set The method of setting up a new

agreement will enable the new agreement

25
2.7 sendfile File Support

26
2.8 SSL stand by

SSL stand by

This chapter will explain in detail how to make and how to turn a certificate Swoole of SSL One-way, two-way authentication.

Ready to work

Select any path, execute the following command to create the folder structure

mkdir ca cd ca

mkdir private mkdir server

mkdir newcerts

in ca Create a directory openssl.conf File, as follows

27
2.8 SSL stand by

[Ca]

default_ca = Foo # The default ca section

[Foo] dir

= / Path / to / ca # Top dir

database = /path/to/ca/index.txt # Index file.

new_certs_dir = / path / to / ca / ​newcerts # new certs dir

certificate = /path/to/ca/private/ca.crt # The CA cert

serial = / Path / to / ca / ​serial # serial no file

private_key = /path/to/ca/private/ca.key # CA private key

RANDFILE = /path/to/ca/private/.rand # random number file

default_days = 365 # how long to certify for

default_crl_days = 30 # how long before next CRL

default_md = Md5 # message digest method to use

unique_subject = no # Set to 'no' to allow creation of

# several ctificates with same subject.

policy = Policy_any # default policy

[Policy_any] countryName = match stateOrProvinceName

= match organizationName = match

organizationalUnitName = match localityName

= Optional

commonName = Optional

emailAddress = Optional

among them, / path / to / ca / Yes ca Absolute path to the directory.

create ca certificate

in ca Create a directory shell Script, named new_ca.sh . Document reads as follows:

# ! / Bin / sh

openssl genrsa -out private / ca.key

openssl req -new -key private / ca.key -out private / ca.csr

openssl x509 -req -days 365 -in private / ca.csr -signkey private / ca.key -out private / ca

. crt

echo FACE> serial touch index.txt

openssl ca -gencrl -out private / ca.crl -crldays 7 -config "./openssl.conf"

carried out sh new_ca.sh Command to create ca certificate. Generated certificate stored in private Directory.

28
2.8 SSL stand by

note Creating ca Course certificate, you need to enter some information. among them, countryName ,

stateOrProvinceName , organizationName , organizationalUnitName The contents of these four options must be filled out, and to remember. In the

subsequent process of generating a certificate, it is necessary to ensure consistency with the text of the four options.

Create a server certificate

in ca Create a directory shell Script, named new_server.sh . Document reads as follows:

# ! / Bin / sh

openssl genrsa -out server / server.key

openssl req -new -key server / server.key -out server / server.csr

openssl ca -in server / server.csr -cert private / ca.crt -keyfile private / ca.key -out ser ver / server.crt -config "./openssl.conf"

carried out sh new_ca.sh Command to create ca certificate. Generated certificate stored in server Directory.

Creating a client certificate

in ca Create a directory shell Script, named new_client.sh . Document reads as follows:

# ! / Bin / sh

base = "./"

mkdir -p $ Base / Users / openssl genrsa -des3 -out $ Base /users/client.key 1024 openssl req -new -key $ Base /users/client.key -out $ Base /users/client.csr

openssl ca -in $ Base /users/client.csr -cert $ Base /private/ca.crt -keyfile $ Base / Privat e / ca.key -out $ Base /users/client.crt -config "./openssl.conf"

openssl pkcs12 -export -clcerts -in $ Base /users/client.crt -inkey $ Base /users/client.k ey -out $ Base /users/client.p12

carried out sh new_ca.sh Command to create ca certificate. Generated certificate stored in users Directory. enter users Directory, you can see there is

a client.p12 File, this is available to the client certificate, but the certificate is not in php

Used, it is necessary to do a conversion. Command is as follows:

openssl pkcs12 -clcerts -nokeys -out cer.pem -in client.p12 openssl pkcs12 -nocerts -out key.pem -in

client.p12

The above command will generate two cer.pem with key.pem Two files. Wherein generating key.pem When will be asked to set a password, write here client_pwd

29
2.8 SSL stand by

note If you create a client certificate, it has to client.p12 A password is set, then the time format conversion, a password is required to

convert

Final Results

After completion of the above steps, you will get a lot of files, wherein the file shown in the following table need to: | filename | path | Description | | --- | --- | --- | | ca.crt

| ca / ​private / | ca Certificates | | server.crt | ca / ​server / | Server-side certificates | |

server.key | ca / ​server / | Server-side keys | | cer.pem | ca / ​client / | Client Certificate | | key.pem | ca / ​client / | The client keys |

SSL One-way authentication

Swoole Open SSL

Swoole Open SSL Function requires the following parameters:

$ Server = new swoole_server ( "127.0.0.1" , "9501" , SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SW OOLE_SSL); $ server = new swoole_http_server ( "127.0.0.1"

, "9501" , SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);

And swoole Configuration options to add the following two options:

$ Server-> set ( array (

'Ssl_cert_file' => '/path/to/server.crt' ,

'Ssl_key_file' => '/path/to/server.key' ,

) );

At this time, swoole Server has opened the way SSL Certified by https://127.0.0.1:9501/ Access.

SSL Mutual Authentication

Server-side settings

Mutual authentication server also means that the client initiated the request for certification, only accessible by authenticated clients can. In order to open SSL

Mutual authentication, swoole The need for additional configuration parameters are as follows:

30
2.8 SSL stand by

$ Server-> set ( array (

'Ssl_cert_file' => '/path/to/server.crt' ,

'Ssl_key_file' => '/path/to/server.key' ,

'Ssl_client_cert_file' => '/path/to/ca.crt' ,

'Ssl_verify_depth' => 10 ,

) );

Client Settings

Here we use CURL get on https Requests initiated. First, you need to configure php.ini, Add the following configuration:

curl.cainfo = / path / to / ca.crt

Launch curl Request, add the following configuration items:

$ Ch = curl_init ();

curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, '2' ); Curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, true ); // Only trust CA Certificate

issued

curl_setopt ($ ch, CURLOPT_SSLCERT, "/path/to/cer.pem" ); Curl_setopt ($ ch, CURLOPT_SSLKEY, "/path/to/key.pem" ); Curl_setopt ($ ch,

CURLOPT_SSLCERTTYPE, 'PEM' ); Curl_setopt ($ ch, CURLOPT_SSLCERTPASSWD, '******' ); // Create a client certificate mark client_pwd password

At this point, you can initiate a https Request, and is swoole Verified by the server.

31
Appendix * Configuration Options

Configuration Options

[TOC]

in swoole In a swoole_server Relevant attributes can be

$ Serv-> set ( array $ Configs);

Function to configure, make these configuration options swoole More flexible. Example:

$ Serv = new swoole_server ( "0.0.0.0" , 9501 ); $ Serv-> set ( array (

'Worker_num' => 8 ,

'Max_request' => 10000 ,

'Max_conn' => 100 000 ,

'Dispatch_mode' => 2 ,

'Debug_mode' => 1 ,

'Daemonize' => false ,

) );

Configuration options and related presentations are as follows:

reactor_num

Description: Specifies Reactor Threads

Description: The main course of events set number of processing threads, enabled by default CPU Audit same number is usually set to

CPU Audit of 1-4 Times, shall not exceed the maximum CPU Audit * 4 . Example:

'Reactor_num' => 8

worker_num

Description: Specifies the boot worker The number of processes Description: open worker The more the number of processes, server The larger load capacity, but

the corresponding server It will occupy more memory. Meanwhile, when worker When too many processes, inter-process switching overhead caused will be

greater. It is proposed to open worker Number of processes cpu Audit of 1-4 Times. Example:

32
Appendix * Configuration Options

'Worker_num' => 8

max_request

Description: Each worker Process to allow the maximum number of tasks processed. Description: Set the value of each worker In the process of processed max_request

It will automatically restart after a request. The set values ​for the primary purpose is to prevent worker Memory overflow may cause the process to handle a large

number of requests. Example:

'Max_request' => 10000

max_conn

Description: The server allows maintaining maximum TCP Connections

Description: After setting this parameter, the number of connections existing when the server reaches this value, the new connection is refused. The value of

this parameter can not exceed the operating system ulimit -n Value, but this value should not be set too high, because swoole_server It will be a one-time

application for a chunk of memory for storing each connection Information. Example:

'Max_conn' => 10000

ipc_mode

Description: communication between setting process. Description:

There are three communication methods, the following parameters:

1 => use unix socket Communicate

2 => Communication using message queues

3 => Communication using message queues, and the mode is set to compete for

Example:

'Ipc_mode' => 1

dispatch_mode

33
Appendix * Configuration Options

Description: Specifies the packet distribution policy.

Description: There are three modes, parameters are as follows:

1 => Round Robin mode, will receive round-robin assigned to each worker process

2 => Fixed pattern, according to the file descriptor allocated connection worker . This ensures that the same connection data will only be sent to

the same worker deal with

3 => Preemption mode, the main process will be based on Worker The busy state selection delivery, only delivered to the idle state Worker

Example:

'Dispatch_mode' => 2

task_worker_num

Description: The server open task The number of processes. Description: This parameter is set, the server will open asynchronous task Features. At this point

you can use task The method of delivery of asynchronous tasks.

After you set this parameter, you must give swoole_server Set up onTask / onFinish Two callback functions, or starts the server error.

Example:

'Task_worker_num' => 8

task_max_request

Description: Each task Process to allow the maximum number of tasks

processed. Note: Reference max_request task_worker_num

Example:

'Task_max_request' => 10000

task_ipc_mode

Description: Set task Process and worker Way communication between processes. Note:

Reference ipc_mode

Example:

34
Appendix * Configuration Options

'Task_ipc_mode' => 2

task_tmpdir

Description: Set task The data in the temporary directory Note: swoole_server If the delivery of data over 8192 Byte, will enable the temporary file to

store data. here task_tmpdir It is used to set the location to save temporary files.

need swoole-1.7.7 +

Example:

'Task_tmpdir' => '/ Tmp / task /'

daemonize

Description: Set into the program running in the background as a daemon.

Description: The long-running server program must enable this. If the daemon is not enabled, when ssh After the terminal exit, the program will be terminated

run. When enabled daemon, standard input and output will be redirected to log_file ,in case log_file Is not set, all output is discarded. Example:

'Daemonize' => 0

log_file

Description: Specifies the path to the log file Explanation: swoole Information on the occurrence of abnormal operation will be recorded in this file. The

default will be printed to the screen. note

log_file Not automatic segmentation file, this file needs to be cleaned regularly. Example:

'Log_file' => '/data/log/swoole.log'

log_level

35
Appendix * Configuration Options

Description: Set swoole_server Level error log to print: Level range 0-5 Below log_level Set the

log information will not be thrown.

Example:

'Log_level' => '1

heartbeat_check_interval

Description: Sets the heartbeat interval

Description: This option indicates how often polling time, in seconds. Detecting when all connections of each iteration, if a data connection is not transmitted

during the interval, is forced to close the connection (there onClose Callback). Example:

'Heartbeat_check_interval' => 60

heartbeat_idle_time

Description: Set a connection to allow the maximum idle time. Description: This parameter fit heartbeat_check_interval use. Each time through all

the connections, if a connection heartbeat_idle_time No data is sent within the time, it is forced to close the connection. The default setting is heartbeat_check_interval

* 2 . Example:

'Heartbeat_idle_time' => 600

open_eof_split

Description: Open eof Detection Function: and package_eof With the use of. This option will be sent to client connection detection data, when the data packet is

the designated end package_eof String will only be delivered to the packet Worker Process, otherwise it would have been spliced ​packet buffer overflow or until a

timeout before termination. Once an error, the connection is determined to be malicious connection, packets are discarded and forcibly close the connection.

EOF Does not find the data detected from the intermediate eof String, Worker Process may also receive a plurality of packets, the application layer requires

its own code explode ( "\ r \ n", $ data) To split the data packet

Example:

36
Appendix * Configuration Options

'Open_eof_split' => true

package_eof

Description: Set EOF String Description: package_eof The maximum allow incoming 8 Example

bytes string:

'Package_eof' => '/ R / n'

open_length_check

Description: Open packet length detector

Description: parsing packet length detector is provided fixed format protocol packet header + body. When enabled, you can guarantee Worker process

onReceive Each will receive a complete packet. Example:

'Open_length_check' => true

package_length_offset

Description: The header byte it begins storing the length field descriptions: complex open_length_check Use, for

the length field indicating the position. Example:

'Package_length_offset' => 5

package_body_offset

Description: length counted from the first few bytes. Description: with open_length_check Used for

indicating the length of the header. Example:

'Package_body_offset' => 10

37
Appendix * Configuration Options

package_length_type

Description: Specifies the packet length field Type Description: with open_length_check , Specify the length of the field types,

parameters are as follows:

'S' => int16_t Machine endian

'S' => uint16_t Machine endian

'N' => uint16_t Big endian

'N' => uint32_t Big endian

'L' => uint32_t Machine endian

'L' => int Machine endian

Example:

'Package_length_type' => 'N'

package_max_length

Description: Set the maximum packet size

Description: This value determines the size of the data packet cache. If the cached data exceeds this value, an error is thrown. Error handling specific types of

decisions resolved by agreement open. Example:

'Package_max_length' => 8192

open_cpu_affinity

Description: Enables CPU Affinity settings

Note: In multi-core hardware platforms, will enable this feature swoole of reactor Thread / worker Process bound to a core fixed. Avoid running

process / thread when switch between multiple cores, improving CPU Cache The hit rate. Example:

'Open_cpu_affinity' => true

cpu_affinity_ignore

38
Appendix * Configuration Options

Description: Sets the specified CPU Nuclear Description: IO Intensive program, all the network interrupts are used CPU0 To deal with, if the network IO Heavy, CPU0 The

load is too high will lead to network outages not been able to handle that capacity network transceiver package will drop. This parameter is used to set a specific

CPU Kernel vacated designed to handle network outages. It accepts an array as a parameter, array (0, 1) They

said they did not use CPU0, CPU1

This option must open_cpu_affinity Also set to take effect

Example:

'Cpu_affinity_ignore' => array ( 0 , 1 )

open_tcp_nodelay

Description: Enables open_tcp_nodelay

Description: open after TCP Will be closed when no send data Nagle Merging algorithm, immediately sent to the client connection. In some scenarios, such as http Server,

you can improve the speed of response. Example:

'Open_tcp_nodelay' => true

tcp_defer_accept

Description: Enables tcp_defer_accept Characteristics: After starting only one TCP It will trigger the

connection data is sent accept . Example:

'Tcp_defer_accept' => true

open_tcp_keepalive

Description: Open TCP of KEEP_ALIVE Option Description: Use TCP Built-in keep_alive Attribute, ensure that the connection will not be idle for a

long time been closed. Example:

'Open_tcp_keepalive' => true

39
Appendix * Configuration Options

tcp_keepidle

Description: Specifies the interval detection. Description: with open_tcp_keepalive Use, if a connection tcp_keepidle No data to and from within, is to

be detected. Example:

'Tcp_keepidle' => 600

tcp_keepinterval

Description: Specifies the sending interval detection

Description: with open_tcp_keepalive Example of use:

'Tcp_keepinterval' => 60

tcp_keepcount

Description: Specifies the number of attempts to detect explanation: with open_tcp_keepalive Use, if tcp_keepcount After attempts still no response, it is

determined that the connection has been closed. Example:

'Tcp_keepcount' => 5

backlog

Description: Specifies Listen Queue Length

Description: This parameter determines how many wait while most accept Connection. Example:

'Backlog' => 128

chroot

40
Appendix * Configuration Options

Description: The redirector Worker File system root directory of the process

Description: This setting allows a process to read and write to the file system and the actual operating system file system isolation. Improve security.

need swoole-1.7.9 +

Example:

'Chroot' => '/ Data / server /'

user / group

Description: Set worker / task The child belongs to the user / user group

Description: This setting allows a process to read and write to the file system and the actual operating system file system isolation. Improve security.

need swoole-1.7.9 + Only use root Effective when users start

Example:

'User' => 'Www' 'group' => 'Www'

discard_timeout_request

Description: Set whether the drop request has timed instructions: swoole In the configuration dispatch_mode = 1 or 3 , The system can not be guaranteed onConnect

/ onReceive / onClose

Sequence, so there may be some request data after connection is closed, in order to reach Worker process.

discard_timeout_request Configuration defaults true , Said that if worker Has closed the connection process received data request, it will automatically

discarded. discard_timeout_request If set to false Indicating whether the connection is closed

Worker Process will handle data requests. need swoole-1.7.16 +

Example:

'Discard_timeout_request' => true

enable_reuse_port

Description: Sets the port reuse Description: This parameter is used to optimize TCP connected Accept Multiple processes can be carried out

simultaneously after the performance, enable port reuse

Accept operating.

41
Appendix * Configuration Options

only at Linux-3.9.0 Or later kernel available

Example:

'Enable_reuse_port' => true

ssl_cert_file with ssl_key_file

Description: Set SSL Encrypted tunnel

Description: Sets the value of a file name string, designated cert Certificate and key path of. Example:

'Ssl_cert_file' => '/config/ssl.crt' ,

'Ssl_key_file' => '/config//ssl.key' ,

ssl_client_cert_file

Description: Specifies CA Certification Path Description: open two-way SSL Authentication, you need to

specify the client used CA certificate

Example:

'Ssl_client_cert_file' => '../ca.crt'

ssl_verify_depth

Description: Length Description Set client certificate

authentication chain: open two-way SSL Authentication using

Example:

'Ssl_verify_depth' => 1

ssl_method

Description: Set OpenSSL Tunnel encryption algorithm description: Server versus Client The algorithm used must be consistent, otherwise SSL / TLS Handshake

fails, the connection will be cut off. The default algorithm SWOOLE_SSLv23_METHOD

42
Appendix * Configuration Options

SWOOLE_SSLv3_METHOD SWOOLE_SSLv3_SERVER_METHOD SWOOLE_SSLv3_CLIENT_METHOD

SWOOLE_SSLv23_METHOD (Default encryption method)

SWOOLE_SSLv23_SERVER_METHOD SWOOLE_SSLv23_CLIENT_METHOD

SWOOLE_TLSv1_METHOD SWOOLE_TLSv1_SERVER_METHOD SWOOLE_TLSv1_CLIENT_METHOD

SWOOLE_TLSv1_1_METHOD SWOOLE_TLSv1_1_SERVER_METHOD

SWOOLE_TLSv1_1_CLIENT_METHOD SWOOLE_TLSv1_2_METHOD

SWOOLE_TLSv1_2_SERVER_METHOD SWOOLE_TLSv1_2_CLIENT_METHOD

SWOOLE_DTLSv1_METHOD SWOOLE_DTLSv1_SERVER_METHOD

SWOOLE_DTLSv1_CLIENT_METHOD

Example:

'Ssl_method' => SWOOLE_SSLv23_METHOD

ssl_ciphers

Description: Configuration SSL Encryption Kit Description: Enables http2 After the agreement, Chrome / Firefox Other browsers required to use strong encryption

suite. Some low-browser version may not support the default cipher suites, can be set to an empty string version of the browser is compatible low

Example:

'Ssl_ciphers' => 'EECDH + AESGCM: EDH + AESGCM: AES256 + EECDH: AES256 + EDH'

43
Appendix * callback function

44
* Appendix property list

45
Appendix * List of functions

03.swoole_server Function List

[TOC]

swoole_server :: __ construct

Description: create a swoole_server Resource Object Prototype:

// Class member functions

public function swoole_server :: __construct (String $ host, int $ port, int $ mode = SWOOLE _PROCESS,

int $ sock_type = SWOOLE_SOCK_TCP) ;

// Public function

function swoole_server_create (String $ host, int $ port, int $ mode = SWOOLE_PROCESS,

int $ sock_type = SWOOLE_SOCK_TCP) ;

Returns: a swoole_server Object

Parameters:

parameter Explanation

string host Listening IP address

int port Listening port number

int mode Run mode

int sock_type Specified socket Types of

Description: host , port , socket_type See detailed description swoole_server :: addlistener .

mode Specified swoole_server Mode of operation, there are the following three:

46
Appendix * List of functions

mode Types of Explanation

The traditional asynchronous non-blocking Server . in Reactor Directly within the callback PHP

Base The function. If the callback function has a blocking action causes Server Degenerate into
SWOOLE_BASE
mode synchronous mode. worker_num Parameters and BASE Mode is still active, swoole Multiple

starts Reactor process

Threaded Multithreading Worker mode, Reactor Polling thread to handle network events, read the data.

mode The resulting request to Worker Thread to handle. Multi-threaded mode than the lightweight

SWOOLE_THREAD (deprecated) process model, and can stack and share resources between threads. There will be

synchronization problems when accessing shared memory is required Swoole Lock

mechanisms to protect data.

Process
Swoole It provides a complete process management, memory protection mechanisms. In the
mode
SWOOLE_PROCESS business logic is very complex cases, can also be a long-term stable operation for the
(default)
business logic is very complex scenes.

Example:

$ Serv = new swoole_server ( "127.0.0.1" , 8888 , SWOOLE_PROCESS, SWOOLE_SOCK_TCP);

swoole_server :: set

Function Description: Set swoole_server The parameters of the function prototype

runtime:

// Class member functions

public function swoole_server :: set (Array $ setting) ;

// Public function

function swoole_server_set (Swoole_server $ server, array $ setting) ;

Returns: None

Parameters:

parameter Explanation

array setting Array of configuration options, the use of key-value form

Description:

This function must swoole_server :: start Function call before the call. Complete swoole_server

Configuration parameters Click here to view

Example:

47
Appendix * List of functions

$ Serv-> set (

array (

'Worker_num' => 8 ,

'Max_request' => 10000 ,

'Max_conn' => 100 000 ,

'Dispatch_mode' => 2 ,

'Debug_mode' => 1 ,

'Daemonize' => false ,

);

swoole_server :: on

Description: Bind swoole_server Related callback function prototype:

// Class member functions

public function bool swoole_server -> on (String $ event, mixed $ callback) ;

Returns: Setting successful return true Otherwise false

Parameter Description:

parameter Explanation

string event The name of the callback (not case sensitive)

mixed Callback PHP Function, can be a string function name, class static methods, object methods, arrays, anonymous

callback functions

Description:

This function must swoole_server :: start Function call before the call. This method swoole_server :: handler The same function,

role and swoole_client Style consistent.

swoole_server :: on Do not add the name of a string of events on . All

callback list Click here to view

Example:

$ Serv-> on ( 'Connect' , function ($ Serv, $ fd) {

echo "Client:. Connect \ n" ;});

$ Serv-> on ( 'Receive' , array ($ Myclass, 'OnReceive' )); // onReceive Yes myclass Member function

swoole_server :: addlistener

48
Appendix * List of functions

Function description: swoole_server Add address and port function prototype of a listener:

// Class member functions

public function swoole_server :: addlistener (String $ host, int $ port, $ type = SWOOLE_SOC K_TCP) ;

// Public function

function swoole_server_addlisten (Swoole_server $ serv, string $ host, int $ port, $ type = SWOOLE_SOCK_TCP) ;

Returns: None

Parameters:

parameter Explanation

string host Listening IP address

int port Listening port number

int sock_type Specified socket Types of

Description: swoole It supports the following socket Types of:

sock_type Explanation

SWOOLE_TCP / SWOOLE_SOCK_TCP TCP IPv4 Socket

SWOOLE_TCP6 / SWOOLE_SOCK_TCP6 TCP IPv6 Socket

SWOOLE_UDP / SWOOLE_SOCK_UDP UDP IPv4 Socket

SWOOLE_UDP6 / SWOOLE_SOCK_UDP6 UDP IPv4 Socket

SWOOLE_UNIX_DGRAM Unix UDP Socket

SWOOLE_UNIX_STREAM Unix TCP Socket

Unix Socket only at 1.7.1+ After available, this mode host Parameters must complete file path accessible, port Parameter is ignored

Unix Socket Mode, client fd It will no longer be a number, but a string file path

SWOOLE_TCP And so is 1.7.0+ After providing a shorthand way, and 1.7.0 Before SWOOLE_SOCK_TCP It is equivalent

Example:

49
Appendix * List of functions

$ Serv-> addlistener ( "127.0.0.1" , 9502 , SWOOLE_SOCK_TCP); $ serv-> addlistener ( "192.168.1.100" , 9503 ,

SWOOLE_SOCK_TCP); $ serv-> addlistener ( "0.0.0.0" , 9504 , SWOOLE_SOCK_UDP); $ serv-> addlistener ( "/var/run/myserv.sock"

, 0 , SWOOLE_UNIX_STREAM);

swoole_server_addlisten ($ serv, "127.0.0.1" , 9502 , SWOOLE_SOCK_TCP);

swoole_server :: handler

Function Description: Set Server The event callback function

prototype:

// Class member functions

public function swoole_server :: handler (String $ event_name, mixed $ event_callback_funct ion) ;

// Public function

function swoole_server_handler (Swoole_server $ serv, string $ event_name, mixed $ event_c allback_function) ;

Returns: Setting successful return true Otherwise false

Parameter Description:

parameter Explanation

string event_name The name of the callback (not case sensitive)

mixed
event_callback_function Callback PHP Function, can
Like array be a string
of methods, functionfunctions
anonymous name, class static methods,

Description: This function must swoole_server :: start Function call before the call. Event name

string to add on . All callback list Click here to view

onConnect / onClose / onReceive This 3 Callback function must be set. Other optional event callback function if it is set timer Timers,

onTimer Event callback function must also be set if enabled task_worker , onTask / onFinish Event callback function must be set

Example:

$ Serv-> handler ( 'OnStart' , 'My_onStart' ); $ Serv-> handler ( 'OnStart' , array ($ This, 'My_onStart' )); $

Serv-> handler ( 'OnStart' , 'MyClass :: onStart' );

50
Appendix * List of functions

swoole_server :: start

Description: Start server , Begins listening for all TCP / UDP Port Prototype:

// Class member functions

public function swoole_server :: start ()

Returns: Start a successful return true Otherwise false

Parameters: None

Description:

Created after a successful start worker_num + 2 A process: Master Process + Manager Process + worker_num More

Worker process. In addition. Enable task_worker Increases task_worker_num More Worker Description process

three kinds of processes as follows:

Process Type Explanation

Master The main process has more than Reactor Thread, based on epoll / kqueue Network event polling. After receiving the data forwarded

process to the Worker Process to deal with

Manager All Worker Process management, Worker End of Life process or automatic recovery when an exception occurs, and create a new Worker

process process

Worker
Processing the data received, and the response request comprises a protocol analysis
process

Example:

$ Serv-> start ();

swoole_server :: reload

Description: Restart all worker process.

Prototype:

// Class member functions

public function swoole_server :: reload ()

Returns: call returns successfully true Otherwise false

Parameters: None

Description:

51
Appendix * List of functions

After the call will Manager Send a SIGUSR1 Signal, all of GR Worker Process (called GR refers to the action will restart Worker Occur

after handling the task being performed and does not interrupt running tasks. )

Tip: In onWorkerStart Callback require corresponding php File, when the file is modified only through

SIGUSR1 The signal can be realized hot update server.

1.7.7 Version adds only restart task_worker Function. Just send to the server SIGUSR2 You can sample:

$ Serv-> reload ();

swoole_server :: shutdown

Description: Shut down the server.

Prototype:

// Class member functions

public function swoole_server :: shutdown ()

Returns: call returns successfully true Otherwise false

Parameters: None

Description:

This function can be used in worker In the process, turn off all smooth Worker process. Also to Master Send

process SIGTERM Signal off the server. Example:

$ Serv-> shutdown ();

swoole_server :: addtimer

Function Description: Sets a fixed interval timer function

prototype:

// Class member functions

public function swoole_server :: addtimer (Int $ interval) ;

// Public function

function swoole_server_addtimer (Swoole_server $ serv, int $ interval) ;

Returns: Setting successful return true Otherwise false

Parameter Description:

52
Appendix * List of functions

parameter Explanation

int interval Timer interval, in milliseconds ms

Description:

swoole Timer is the smallest particles 1 Ms, supports a plurality of different intervals timers. Be careful not exist 2 Timers

of the same interval of time.

When using a plurality of timers, the other timer must be a multiple of the minimum interval timer.

This function can only be onWorkerStart / onConnect / onReceive / onClose Call the callback function. After the timer needs to

be increased Server Set up onTimer Callback, otherwise Server Will not start.

Example:

$ Serv-> addtimer ( 1000 ); // 1s

swoole_server_addtimer ($ serv, 20 ); // 20ms

swoole_server :: deltimer

Description: Deletes the specified timer.

Prototype:

// Class member functions

public function swoole_server :: deltimer (Int $ interval) ;

Returns: None

Parameters:

parameter Explanation

int interval Timer interval, in milliseconds ms

Description: Removes interval interval Timer

Example:

$ Serv-> deltimer ( 1000 );

swoole_server :: after

53
Appendix * List of functions

Function Description: The function prototype function

performed after a specified time:

// Class member functions

public function swoole_server :: after (Int $ after_time_ms, mixed $ callback_function, mix ed params) ;

// Public function

function swoole_timer_after (Swoole_server $ serv, int $ after_time_ms , mixed $ callback_f unction, mixed params) ;

Returns: None

Parameters:

parameter Explanation

int after_time_ms Specify the time, in milliseconds ms

mixed callback_function Specified callback function

mixed params Parameter specifies the callback function

Description:

Creating a one-time timer, specified after_time_ms After calling time callback_funciton Callback function will be after the execution is complete destruction.

callback_function Function parameters specified params

need swoole-1.7.7 Above.

Example:

$ Serv-> after ( 1000 , function ($ Params) {

echo "Do something \ n" ;}, "Data" );

swoole_server :: close

Description: Close client connection function

prototype:

// Class member functions

public function swoole_server :: close (Int $ fd, int $ from_id = 0) ;

Returns: close the successful return true , Failed to return false

Parameter Description:

54
Appendix * List of functions

parameter Explanation

int fd Designated off fd

int from_id fd From which Reactor ( swoole-1.6 After the parameter obsolete)

Description: Call close After closing the connection, the connection will not immediately shut down, so do not close Immediately after the write logic to clean up, but

should be onClose Callback processing

Example:

$ Serv-> close ($ fd);

swoole_server :: send

Description: transmitting data to a client function

prototype:

// Class member functions

public function swoole_server :: send (Int $ fd, string $ data, int $ from_id = 0) ;

Returns: Send a successful return true , Failed to return false

Parameter Description:

parameter Explanation

int fd Specify sent fd

string data Data transmission

int from_id fd From which Reactor

Description:

data The transmitted data, shall not exceed the maximum 2M . send Having atomic operation, a plurality of calls simultaneously processes send A

transmission connected to the same data, mixed data does not occur. If you want to send more than 2M Data, it is recommended to write data to a

temporary file, and then sendfile Interface directly send files

UDP protocol, send Directly in worker Send packets to the in-process UDP The

client sends data, must be passed from_id

Sent successfully returns true , If the connection has been closed or failed return false swoole-1.6 Above do not need from_id

UDP Protocol fd Save client IP , from_id save from_fd with port UDP If the agreement is in onReceive Immediately after

sending the data to the client, may not pass from_id

55
Appendix * List of functions

Example:

$ Serv-> send ($ fd, "Hello World" );

swoole_server :: sendfile

Description: send the file to TCP Client connection

Prototype:

// Class member functions

public function swoole_server :: sendfile (Int $ fd, string $ filename) ;

Returns: Send a successful return true , Failed to return false

Parameter Description:

parameter Explanation

int fd Specify sent fd

string filename Send the file name

Description:

sendfile Function call OS which provided sendfile System calls, read by the operating system and write directly to the file socket .

sendfile only 2 Second memory copy, use this function can reduce operating system when sending large numbers of files CPU And memory footprint.

Example:

$ Serv-> sendfile ($ fd, __DIR__ . '/test.jpg' );

swoole_server :: connection_info

Function Description: acquiring information

connection function prototype:

// Class member functions

public function swoole_server :: connection_info (Int $ fd, int $ from_id = 0) ;

Returns: fd Exists, returns an array, there is no connection or closed return false

Parameter Description:

56
Appendix * List of functions

parameter Explanation

int fd Specify sent fd

int from_id From which Reactor

Description:

UDP socket This parameter must be passed when calling from_id.

Returned results are as follows:

name Explanation

int from_id From which Reactor

int from_fd From which Server Socket

int from_port From which Server port

int remote_port Port client connections

string remote_ip Client connections ip

int connect_time Connected to Server The time, in seconds

int last_time Last time of transmitting data, in seconds

sendfile Function call OS which provided sendfile System calls, read by the operating system and write directly to the file socket .

sendfile only 2 Second memory copy, use this function can reduce operating system when sending large numbers of files CPU And memory footprint.

Example:

$ Fdinfo = $ serv-> connection_info ($ fd);

$ Udp_client = $ serv-> connection_info ($ fd, $ from_id);

swoole_server :: connection_list

Description: The current traversal Server All client connections Prototype:

// Class member functions

public function swoole_server :: connection_list (Int $ start_fd = 0, int $ pagesize = 10) ;

Returns: the call is successful will return a numerically indexed array element is taken to the fd . Array will be in ascending order. the last one fd As the new start_fd

Try to get it again. Call failed to return false

Parameter Description:

57
Appendix * List of functions

parameter Explanation

int start_fd Starting fd

int pagesize How many page take, shall not exceed the maximum 100.

Description:

connection_list Only be used TCP , UDP Servers need to preserve client information on their own

Example:

$ Start_fd = 0 ;

while ( true ) {

$ Conn_list = $ serv-> connection_list ($ start_fd, 10 );

if ($ Conn_list === false ) {

echo "Finish \ n" ;

break ;}

$ Start_fd = end ($ conn_list); var_dump ($

conn_list);

foreach ($ Conn_list as $ Fd) {

$ Serv-> send ($ fd, "Broadcast" );

}}

swoole_server :: stats

Function Description: Get the current Server activity TCP The number of connections, start time, accpet / close The total number and other information.

Prototype:

// Class member functions

public function swoole_server -> stats () ;

Returns: the resulting array

Parameters: None

Description:

stats Methods 1.7.5+ Available after

58
Appendix * List of functions

name Explanation

int start_time Start Time

int connection_num The current number of connections

int accept_count accept The total number of

int close_count close The total number of connections

Example:

$ Status = $ serv-> stats ();

swoole_server :: task

Description: asynchronous task to deliver a task_worker Pool Prototype:

// Class member functions

public function swoole_server :: task (String $ data, int $ dst_worker_id = -1) ;

Returns: call returns successfully task_worker_id , Failed to return false

Parameter Description:

parameter Explanation

string data task data

int dst_worker_id To which the specified delivery task Process, the default random delivery

Description:

This function is used to slow task to execute asynchronously, call task Function returns immediately, Worker The process can continue to process new requests.

Function returns a $ task_id Number that represents this task ID

After the task is completed, you can return ( Lower than swoole-1.7.2 Versions finish Function) The results onFinish Returned to the callback Worker

process. Sent data Must, if it is an array or object, in the business code in a string serialize Processing and onTask / onFinish Conducted unserialize

data It may be a binary data, the maximum length of 8K ( exceed 8K You can use a temporary file sharing). You can use a string

gzip Compression. use task It must be Server Set up onTask with onFinish Callback, and specify task_worker_num Configuration parameters.

Example:

59
Appendix * List of functions

$ Task_id = $ serv-> task ( "Some data" );

swoole_server :: taskwait

Description: Drop a task to synchronize task_worker Pool Prototype:

// Class member functions

public function swoole_server :: taskwait (String $ task_data, float $ timeout = 0.5, int $ dst_worker_id = -1) ;

return: task Description result

parameters performed:

parameter Explanation

string data task data

float timeout overtime time

int dst_worker_id To which the specified delivery task Process, the default random delivery

Description:

taskwait versus task The method of action of the same, for delivery to an asynchronous task task Process pool for execution. versus task the difference is taskwait It

is blocked waiting until the task is completed or a timeout return. After the task is completed, you can return Direct return results

Example:

$ Task_id = $ serv-> taskwait ( "Some data" , 30 );

swoole_server :: finish

Description: transfer Task Results to worker Process Prototype:

// Class member functions

public function swoole_server :: finish (String $ task_data) ;

Returns: None

Parameters:

60
Appendix * List of functions

parameter Explanation

string data Results

Note: Use swoole_server :: finish Function must be Server Set up onFinish Callback. This function can only be used Task Worker Process onTask

Callback

swoole_server :: finish It is optional. in case Worker Process does not care about the results of task execution, this function can not call this function swoole-1.7.2

Obsolete or later, use return instead. Example:

$ Serv-> finish ( "Result data" );

swoole_server :: heartbeat

Description: heartbeat detection function

prototype:

// Class member functions

public function swoole_server :: heartbeat (Bool $ if_close_connection = true) ;

Returns: None

Parameters:

parameter Explanation

bool if_close_connection Whether to close the connection timeout, default true

Description:

This function initiates a test, all the connections traversing, according to the set heartbeat_check_interval with

heartbeat_idle_time Parameters, those found in idle Connection idle

swoole Default directly shut down these connections, heartbeat These connections will return fd

in case if_close_connection for false ,then heartbeat These returns idle connected fd But does not close the connection

if_close_connection Parameters swoole-1.7.4 Above version is available Sample:

$ Serv-> heartbeat ();

swoole_get_mysqli_sock

61
Appendix * List of functions

Function Description: Get mysqli of socket File descriptor

Prototype:

// Public function

int swoole_get_mysqli_sock (mysqli $ db)

return: mysqli of fd

Parameter Description:

parameter Explanation

mysqli db mysqli Connection

Description: You can mysql of socket Increased swoole , Perform asynchronous MySQL Inquire. If you want to use asynchronous MySQL , You need to compile swoole

Developing - enable-async-mysql swoole_get_mysqli_sock Only supports mysqlnd Even if the drive is asynchronous MySQL Also you need a connection pool,

concurrent SQL There must be multiple connections. Example:

$ Db = new mysqli; $ db-> connect ( '127.0.0.1' , 'Root' , 'Root' , 'Test' ); $ Db-> query ( "Show tables" , MYSQLI_ASYNC);

swoole_event_add (swoole_get_mysqli_sock ($ db), function ($ Db_sock) {

global $ Db;

$ Res = $ db-> reap_async_query (); var_dump ($ res-> fetch_all

(MYSQLI_ASSOC)); swoole_event_exit ();});

swoole_set_process_name

Description: Name of the function prototype set

up the process:

// Public function

void swoole_set_process_name (string $ name);

Returns: None

Parameters:

62
Appendix * List of functions

parameter Explanation

string name Process Name

Description:

After the modification process name, by ps Command will no longer be seen php your_file.php But set a string

in swoole_server_create Prior revised to manager Process Name onStart When call to modify the main process name

onWorkerStart change into worker Process Name

swoole_set_process_name Compatibility issues, priority use PHP Built-in cli_set_process_title Sample function:

woole_set_process_name ( "Swoole server" );

swoole_version

Function Description: Get swoole Extended version number of

the function prototype:

// Public function

string swoole_version ();

return: swoole Extended version number

Parameters: None Description: Example:

echo swoole_version ();

swoole_strerror

Description: The standard Unix Errno Error code into error function prototype:

// Public function

string swoole_strerror (int $ errno);

Returns: parameter error message after

conversion Description:

63
Appendix * List of functions

parameter Explanation

int errno errno error code

Description:

Example:

echo swoole_strerror ($ errno);

swoole_errno

Function Description: Get the last error code function prototype system

call:

// Public function

int swoole_errno ();

Returns: the last error code parameter system call

Description: No Description:

The value of the error code and operating system. But use swoole_strerror The conversion error to error messages. Example:

echo swoole_strerror (swoole_errno ());

swoole_get_local_ip

Description: This function is used to obtain all the network interfaces of the native IP Address

Prototype:

// Public function

array swoole_get_local_ip ();

Returns: interface Named key Associative array Parameters: None Description: Currently only returns IPv4 Address,

return the results will filter out local loop address 127.0.0.1

Sample results returned array ( "eth0" => "192.168.1.100") ; Example:

64
Appendix * List of functions

var_dump (swoole_get_local_ip ());

65

You might also like