Professional Documents
Culture Documents
Easy Swoole - ZH CN - en
Easy Swoole - ZH CN - en
Introduction 1.1
Prologue 1.2
1
7 Application Framework 1.31
2
Introduction
Lancelot (Li Danyang ID: Meow will knock code) from LinkedDestiny Studio (Pull machine chamber)
Company : Bilibili
Description
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
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
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
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
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.
DB Model ThinkPHP 3.2.2 ( Use only Model Module Only Model Used)
5
1.1 Environment to build
[TOC]
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.
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
6
1.1 Environment to build
\ g ++ \
autoconf \
libiconv-hook-dev \ libmcrypt-dev \
libxml2-dev \
libmysqlclient-dev \ libcurl4-openssl-dev
\ libjpeg8-dev \ libpng12-dev \
libfreetype6-dev \
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 /
- - 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
php
Note that the above PHP Compiler option to adjust according to the actual situation. To be sure, any of these compiling options is adjustable
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
export PATH = / usr / local / php / bin: $ PATH export PATH = / usr /
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 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
Secure Transport. For that matter, reinstalling it in a code compiling way is still highly recommanded.
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:
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.
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
9
1.1 Environment to build
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
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 /
Swoole Extended Download Download Extract the source to any directory, execute the following command: Extact the codes to any directory and
cd swoole-src-swoole-1.7.6-stable / phpize
. / Configure sudo
make
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
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
[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
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;
$ This-> serv = new swoole_server ( "0.0.0.0" , 9501 ); $ This-> serv-> set ( array (
'Worker_num' => 8 ,
) );
$ 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 ($
echo "Get Message From Client {$ fd}: {$ data} \ n" ; $ Serv-> send ($ fd, $ data);}
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;
echo "Error: {$ this-> client-> errMsg} [{$ this-> client-> errCode}] \ n" ;}
fwrite (STDOUT, " Please enter a message Please input msg : " );
($ msg);
();
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
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 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
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
) );
);
18
2.2 TaskWorker process
/ **
*/
/ **
*/
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
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
// 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" ;
}, "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
}}
$ Test = new Test (); swoole_timer_after ( 1000 , array ($ Test, "OnAfter" ); // Member variables
});
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
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
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.
else {
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
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 ,
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:
'Package_length_offset' => 0 ,
);
);
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
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
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
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 newcerts
27
2.8 SSL stand by
[Ca]
[Foo] dir
= Optional
commonName = Optional
emailAddress = Optional
create ca certificate
# ! / Bin / sh
openssl x509 -req -days 365 -in private / ca.csr -signkey private / ca.key -out private / ca
. crt
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.
# ! / Bin / sh
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.
# ! / 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
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
server.key | ca / server / | Server-side keys | | cer.pem | ca / client / | Client Certificate | | key.pem | ca / client / | The client keys |
$ 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"
) );
At this time, swoole Server has opened the way SSL Certified by https://127.0.0.1:9501/ Access.
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
'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:
$ 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]
Function to configure, make these configuration options swoole More flexible. Example:
'Worker_num' => 8 ,
'Dispatch_mode' => 2 ,
'Debug_mode' => 1 ,
) );
reactor_num
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
max_conn
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:
ipc_mode
3 => Communication using message queues, and the mode is set to compete for
Example:
'Ipc_mode' => 1
dispatch_mode
33
Appendix * Configuration Options
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
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
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
Example:
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:
daemonize
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
log_file Not automatic segmentation file, this file needs to be cleaned regularly. Example:
log_level
35
Appendix * Configuration Options
Description: Set swoole_server Level error log to print: Level range 0-5 Below log_level Set the
Example:
heartbeat_check_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:
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
package_eof
Description: Set EOF String Description: package_eof The maximum allow incoming 8 Example
bytes string:
open_length_check
Description: parsing packet length detector is provided fixed format protocol packet header + body. When enabled, you can guarantee Worker process
package_length_offset
Description: The header byte it begins storing the length field descriptions: complex open_length_check Use, for
'Package_length_offset' => 5
package_body_offset
Description: length counted from the first few bytes. Description: with open_length_check Used for
'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,
Example:
package_max_length
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
open_cpu_affinity
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:
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
Example:
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,
tcp_defer_accept
Description: Enables tcp_defer_accept Characteristics: After starting only one TCP It will trigger the
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
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_keepinterval
'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
'Tcp_keepcount' => 5
backlog
Description: This parameter determines how many wait while most accept Connection. Example:
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:
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.
Example:
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
Example:
enable_reuse_port
Description: Sets the port reuse Description: This parameter is used to optimize TCP connected Accept Multiple processes can be carried out
Accept operating.
41
Appendix * Configuration Options
Example:
Description: Sets the value of a file name string, designated cert Certificate and key path of. Example:
ssl_client_cert_file
Description: Specifies CA Certification Path Description: open two-way SSL Authentication, you need to
Example:
ssl_verify_depth
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_SSLv23_SERVER_METHOD SWOOLE_SSLv23_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_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
[TOC]
swoole_server :: __ construct
public function swoole_server :: __construct (String $ host, int $ port, int $ mode = SWOOLE _PROCESS,
// Public function
Parameters:
parameter Explanation
mode Specified swoole_server Mode of operation, there are the following three:
46
Appendix * List of functions
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
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
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:
swoole_server :: set
runtime:
// Public function
Returns: None
Parameters:
parameter Explanation
Description:
This function must swoole_server :: start Function call before the call. Complete swoole_server
Example:
47
Appendix * List of functions
$ Serv-> set (
array (
'Worker_num' => 8 ,
'Dispatch_mode' => 2 ,
'Debug_mode' => 1 ,
);
swoole_server :: on
Parameter Description:
parameter Explanation
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,
Example:
$ 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:
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
sock_type Explanation
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
, 0 , SWOOLE_UNIX_STREAM);
swoole_server :: handler
prototype:
// Public function
Parameter Description:
parameter Explanation
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
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' )); $
50
Appendix * List of functions
swoole_server :: start
Description: Start server , Begins listening for all TCP / UDP Port Prototype:
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
Master The main process has more than Reactor Thread, based on epoll / kqueue Network event polling. After receiving the data forwarded
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:
swoole_server :: reload
Prototype:
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
1.7.7 Version adds only restart task_worker Function. Just send to the server SIGUSR2 You can sample:
swoole_server :: shutdown
Prototype:
Parameters: None
Description:
This function can be used in worker In the process, turn off all smooth Worker process. Also to Master Send
swoole_server :: addtimer
prototype:
// Public function
Parameter Description:
52
Appendix * List of functions
parameter Explanation
Description:
swoole Timer is the smallest particles 1 Ms, supports a plurality of different intervals timers. Be careful not exist 2 Timers
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:
swoole_server :: deltimer
Prototype:
Returns: None
Parameters:
parameter Explanation
Example:
swoole_server :: after
53
Appendix * List of 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
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.
Example:
swoole_server :: close
prototype:
Parameter Description:
54
Appendix * List of functions
parameter Explanation
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
Example:
swoole_server :: send
prototype:
public function swoole_server :: send (Int $ fd, string $ data, int $ from_id = 0) ;
Parameter Description:
parameter Explanation
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
UDP protocol, send Directly in worker Send packets to the in-process UDP The
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
55
Appendix * List of functions
Example:
swoole_server :: sendfile
Prototype:
Parameter Description:
parameter Explanation
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:
swoole_server :: connection_info
Parameter Description:
56
Appendix * List of functions
parameter Explanation
Description:
name Explanation
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:
swoole_server :: connection_list
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
Parameter Description:
57
Appendix * List of functions
parameter Explanation
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 ) {
break ;}
conn_list);
}}
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:
Parameters: None
Description:
58
Appendix * List of functions
name Explanation
Example:
swoole_server :: task
Parameter Description:
parameter Explanation
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.
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
swoole_server :: taskwait
public function swoole_server :: taskwait (String $ task_data, float $ timeout = 0.5, int $ dst_worker_id = -1) ;
parameters performed:
parameter Explanation
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:
swoole_server :: finish
Returns: None
Parameters:
60
Appendix * List of functions
parameter Explanation
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
swoole_server :: heartbeat
prototype:
Returns: None
Parameters:
parameter Explanation
Description:
This function initiates a test, all the connections traversing, according to the set heartbeat_check_interval with
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
swoole_get_mysqli_sock
61
Appendix * List of functions
Prototype:
// Public function
return: mysqli of fd
Parameter Description:
parameter Explanation
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,
$ Db = new mysqli; $ db-> connect ( '127.0.0.1' , 'Root' , 'Root' , 'Test' ); $ Db-> query ( "Show tables" , MYSQLI_ASYNC);
global $ Db;
swoole_set_process_name
up the process:
// Public function
Returns: None
Parameters:
62
Appendix * List of functions
parameter Explanation
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
swoole_set_process_name Compatibility issues, priority use PHP Built-in cli_set_process_title Sample function:
swoole_version
// Public function
swoole_strerror
Description: The standard Unix Errno Error code into error function prototype:
// Public function
conversion Description:
63
Appendix * List of functions
parameter Explanation
Description:
Example:
swoole_errno
Function Description: Get the last error code function prototype system
call:
// Public function
Description: No Description:
The value of the error code and operating system. But use swoole_strerror The conversion error to error messages. Example:
swoole_get_local_ip
Description: This function is used to obtain all the network interfaces of the native IP Address
Prototype:
// Public function
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
64
Appendix * List of functions
65