May 14, 2021 Swoole
Feature Description:
Create a swoole_server resource object
Function prototype:
// 类成员函数
public function swoole_server::__construct(string $host, int $port, int $mode = SWOOLE_PROCESS,
int $sock_type = SWOOLE_SOCK_TCP);
// 公共函数
function swoole_server_create(string $host, int $port, int $mode = SWOOLE_PROCESS,
int $sock_type = SWOOLE_SOCK_TCP);
Returns:
A swoole_server object
Description of the parameters:
Parameters | Description |
---|---|
string host | The IP address of the listen |
int port | The port number of the listen |
int mode | Run mode |
int sock_type | The specified socket type |
Description:
A detailed description of socket_type, port, and
swoole_server: addlistener.
Mode specifies the swoole_server mode of the system, which are as follows:
mode | Type | Description |
---|---|---|
SWOOLE_BASE | Base mode | Traditional asynchronous non-blocking servers. A function that calls back TOP directly within Realctor. I f there is a blocking operation in the callback function, the server degenerates into synchronization mode. worker_num parameter pair is still valid with BASE mode, swoole starts multipleReactor processes |
SWOOLE_THREAD | Thread mode (abandoned) | Multithreaded Worker mode, reactor threads handle network event polling and read data. T he resulting request is left to the Worker thread for processing. M ultithreaded mode is lighter than process mode, and stacks and resources can be shared between threads. There are synchronization issues when accessing shared memory and you need to use the locking mechanism provided by Swoole to protect your data. |
SWOOLE_PROCESS | Process mode (default) | Swoole provides a sound process management, memory protection mechanism. In situations where business logic is very complex, it can also run steadily for a long time, suitable for scenarios where business logic is very complex. |
Example
:
$serv = new swoole_server("127.0.0.1" , 8888 , SWOOLE_PROCESS , SWOOLE_SOCK_TCP);
Feature Description:
Set swoole_server parameters for the runtime
Function prototype:
// 类成员函数
public function swoole_server::set(array $setting);
// 公共函数
function swoole_server_set(swoole_server $server, array $setting);
Back
: None
Description of the parameters:
Parameters | Description |
---|---|
array setting | Configure an array of options in key-value form |
Description:
The function must
be called swoole_server::start function call before the swoole_server::start
function is called.
All swoole_server the configuration parameters
of this point to view
Example
:
$serv->set(
array(
'worker_num' => 8,
'max_request' => 10000,
'max_conn' => 100000,
'dispatch_mode' => 2,
'debug_mode'=> 1,
'daemonize' => false,
)
);
Feature Description:
Binding swoole_server callback functions of the system
Function prototype:
// 类成员函数
public function bool swoole_server->on(string $event, mixed $callback);
Return:
The setting successfully returns true, otherwise it returns false
Description of the parameters:
Parameters | Description |
---|---|
string event | The name of the callback (case insensitive) |
mixed callback | A PHP function of a callback that can be a string of function names, a class static method, an array of object methods, an anonymous function |
Description:
The function must
be called swoole_server::start function call before the swoole_server::start
function is called.
This method
swoole_server the same function as the :: handler,
and is swoole_client style of the system.
swoole_server::on event
name string do not add on.
All callback functions list
Point here to view
Example
:
$serv->on('connect', function ($serv, $fd){
echo "Client:Connect.\n";
});
$serv->on('receive', array( $myclass, 'onReceive' ) ); // onReceive是myclass的成员函数
Feature Description:
Add swoole_server address and port to the server
Function prototype:
// 类成员函数
public function swoole_server::addlistener(string $host, int $port, $type = SWOOLE_SOCK_TCP);
// 公共函数
function swoole_server_addlisten(swoole_server $serv, string $host, int $port, $type = SWOOLE_SOCK_TCP);
Back
: None
Description of the parameters:
Parameters | Description |
---|---|
string host | The IP address of the listen |
int port | The port number of the listen |
int sock_type | The specified socket type |
Description:
Swoole supports the following socket types:
sock_type | Description |
---|---|
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 is only available after 1.7.1 plus, and the host parameter in this mode must fill in the accessible file path, which is ignored by the port parameter
In Unix Socket mode, the client fd is no longer a number, but a string of file paths
SWOOLE_TCP is a short-form method provided after 1.7.0 plus, which is equivalent to the SWOOLE_SOCK_TCP 1.7.0
Example
:
$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);
Feature Description:
Set the server's event callback function
Function prototype:
// 类成员函数
public function swoole_server::handler(string $event_name, mixed $event_callback_function);
// 公共函数
function swoole_server_handler(swoole_server $serv, string $event_name, mixed $event_callback_function);
Return:
The setting successfully returns true, otherwise it returns false
Description of the parameters:
Parameters | Description |
---|---|
string event_name | The name of the callback (case insensitive) |
mixed event_callback_function | A PHP function of a callback that can be a string of function names, a class static method, an array of object methods, an anonymous function |
Description
: The function must be swoole_server::start function call.
The event name string is to be added.
All callback functions list
Point here to view
The three callback functions onConnect/onClose/onReceive must be set. Other event callback functions are optional
If the timer timer is set, the onTimer event callback function must also be set
If the task_worker enabled, the 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');
Feature Description:
Start the server and start listening to all TCP/UDP ports
Function prototype:
// 类成员函数
public function swoole_server::start()
Return:
Start successfully to return true, otherwise return to false
Parameter Description:
None
Description:
When successfully started, worker_num two processes are created: master processes, Manager processes, worker_num worker processes.
Other than that.
Enabling task_worker will task_worker_num a Worker process
The three processes are described below:
The type of process | Description |
---|---|
Master process | There are multipleReactor threads within the main process that poll for network events based on epoll/kqueue. When the data is received, it is forwarded to the Worker process for processing |
The Manager process | Manage all Worker processes, automatically recycle when the worker process life cycle ends or an exception occurs, and create a new Worker process |
The Worker process | The received data is processed, including protocol resolution and response requests |
Example :
$serv->start();
Feature Description:
Restart all worker processes.
Function prototype:
// 类成员函数
public function swoole_server::reload()
Return:
The call successfully returns true, otherwise the false is returned
Parameter Description:
None
Description:
After the call, a SIGUSR1 signal is sent to Manager to smoothly restart all the Worker processes (so-called smooth restarts, which means that the restart action occurs after the Worker has finished processing the task being performed and does not interrupt the running task).
)
Tip:
Require's corresponding php files in the onWorkerStart
callback, when they are modified, require only a SIGUSR1 signal to achieve server hot updates.
Version 1.7.7 adds the ability to task_worker only.
Simply send SIGUSR2 to the server
Example
:
$serv->reload();
Feature Description:
Shut down the server.
Function prototype:
// 类成员函数
public function swoole_server::shutdown()
Return:
The call successfully returns true, otherwise the false is returned
Parameter Description:
None
Description:
This function can be used to smoothly shut down all worker processes within the worker process.
You can also send a SIGTERM signal to the Master process to shut down the server.
Example
:
$serv->shutdown();
Feature Description:
Set a timer at a fixed interval
Function prototype:
// 类成员函数
public function swoole_server::addtimer(int $interval);
// 公共函数
function swoole_server_addtimer(swoole_server $serv, int $interval);
Return:
The setting successfully returns true, otherwise it returns false
Description of the parameters:
Parameters | Description |
---|---|
int interval | Timer interval in millisecond ms |
Description:
The minimum particle size of the swoole timer is 1 millisecond, which supports timers at multiple different intervals.
Note that there cannot be 2 timers at the same interval.
When using multiple timers, the other timers must be an integer multiple of the minimum timer interval.
This function can only be called in the onWorkerStart/onConnect/onReceive/onClose callback function.
You need to set the
onTimer
callback function for the server after you add the timer, otherwise the server will not start.
Example :
$serv->addtimer(1000); //1s
swoole_server_addtimer($serv,20); //20ms
Feature Description:
Remove the specified timer.
Function prototype:
// 类成员函数
public function swoole_server::deltimer(int $interval);
Back
: None
Description of the parameters:
Parameters | Description |
---|---|
int interval | Timer interval in millisecond ms |
Description:
Remove the timer with an interval interval
Example :
$serv->deltimer(1000);
Feature Description:
Performs a function after a specified time
Function prototype:
// 类成员函数
public function swoole_server::after(int $after_time_ms, mixed $callback_function, mixed params);
// 公共函数
function swoole_timer_after(swoole_server $serv, int $after_time_ms, mixed $callback_function, mixed params);
Back
: None
Description of the parameters:
Parameters | Description |
---|---|
int after_time_ms | Specified time in millisecond ms |
mixed callback_function | The specified callback function |
mixed params | The parameters of the specified callback function |
Description:
Create a one-time timer that calls the after_time_ms callback function after callback_funciton specified time and destroys it when execution is complete.
callback_function of the function is the specified params
A version of swoole-1.7.7 or more is required.
Example :
$serv->after(1000, function( $params ){
echo "Do something\n";
} , "data" );
Feature Description:
Close the client connection
Function prototype:
// 类成员函数
public function swoole_server::close(int $fd, int $from_id = 0);
Return:
Close successfully returns true, fails to return false
Description of the parameters:
Parameters | Description |
---|---|
int fd | Specify the closed fd |
int from_id | fd from which Realctor (swoole-1.6 has discarded the parameter) |
Description:
When you call close the connection, the connection does not close immediately, so instead of writing cleanup logic immediately after
theclose, it should be handled in the onClose
callback
Example :
$serv->close( $fd );
Feature Description:
Send data to the client
Function prototype:
// 类成员函数
public function swoole_server::send(int $fd, string $data, int $from_id = 0);
Return:
Send successfully back to true, fail to return to false
Description of the parameters:
Parameters | Description |
---|---|
int fd | Specifies the fd sent |
string data | The data sent |
int from_id | Which Realctor does fd come from? |
Description:
Example :
$serv->send( $fd , "Hello World");
Feature Description:
Send a file to a TCP client connection
Function prototype:
// 类成员函数
public function swoole_server::sendfile(int $fd, string $filename);
Return:
Send successfully back to true, fail to return to false
Description of the parameters:
Parameters | Description |
---|---|
int fd | Specifies the fd sent |
string filename | The name of the file sent |
Description:
The sendfile function calls the sendfile system call provided by OS, which reads the file directly by the operating system and writes to the socket.
Sendfile has only 2 memory copies, and this function reduces the CPU and memory footprint of the operating system when sending large numbers of files.
Example :
$serv->sendfile($fd, __DIR__.'/test.jpg');
Feature Description:
Get information about the connection
Function prototype:
// 类成员函数
public function swoole_server::connection_info(int $fd, int $from_id = 0);
Return:
If fd exists, return an array, the connection does not exist, or closed returns false
Description of the parameters:
Parameters | Description |
---|---|
int fd | Specifies the fd sent |
int from_id | From which Realctor |
Description:
UDP socket calls this parameter when it must pass in from_id.
The results returned are as follows:
Name | Description |
---|---|
int from_id | From which Realctor |
int from_fd | From which Server Socket |
int from_port | Which Server port is from |
int remote_port | The port to which the client is connected |
string remote_ip | The ip of the client connection |
int connect_time | The time, in seconds, that you connect to the server |
int last_time | The last time data was sent, in seconds |
The sendfile function calls the sendfile system call provided by OS, which reads the file directly by the operating system and writes to the socket.
Sendfile has only 2 memory copies, and this function reduces the CPU and memory footprint of the operating system when sending large numbers of files.
Example :
$fdinfo = $serv->connection_info($fd);
$udp_client = $serv->connection_info($fd, $from_id);
Feature Description:
Traversing all client connections for the current server
Function prototype:
// 类成员函数
public function swoole_server::connection_list(int $start_fd = 0, int $pagesize = 10);
Return:
A successful call returns an array of numeric indexes, and the element is taken to the fd. A
rrays are sorted from small to large.
The last fd as a new start_fd try to get it again.
The call failed to return false
Description of the parameters:
Parameters | Description |
---|---|
int start_fd | Start fd |
int pagesize | How many articles per page, the maximum must not exceed 100. |
Description:
connection_list only available for TCP, the UDP server needs to save client information on its 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");
}
}
Feature Description:
Get information such as the number of active TCP connections for the current server, startup time, total number of accpet/close, and so on.
Function prototype:
// 类成员函数
public function swoole_server->stats();
Returns:
An array of results
Parameter Description:
None
Description:
The stats method is available after 1.7.5 plus
Name | Description |
---|---|
int start_time | Start-up time |
int connection_num | The current number of connections |
int accept_count | Total number of times accepted |
int close_count | The total number of close connections |
Example :
$status = $serv->stats();
Feature Description:
Post an asynchronous task to task_worker pool
Function prototype:
// 类成员函数
public function swoole_server::task(string $data, int $dst_worker_id = -1);
Return:
The call successfully returns task_worker_id and fails to return false
Description of the parameters:
Parameters | Description |
---|---|
string data | Task data |
int dst_worker_id | Specify which task process to post to, which is random by default |
Description:
This feature is used to perform slow tasks asynchronously, calls to the task function are returned immediately, and the Worker process can continue to process new requests.
The function returns a
$task number, representing
the ID of this task
When the task is complete, the results can be returned to the Worker process via the onFinish callback via
the return (using the
finish
function below the swoole-1.7.2 version).
The data sent must be a string, if it is an array or object, in the business code,
and in onTask
/onFinish.
Data can be binary data with a maximum length of
8K (more
than 8K can use temporary file sharing).
Strings can be compressed using gzip.
Using task must set the
onTask and
onFinish callbacks
for the server and specify
the task_worker_num configuration
parameters.
Example :
$task_id = $serv->task("some data");
Feature Description:
Deliver a synchronization task to task_worker pool
Function prototype:
// 类成员函数
public function swoole_server::taskwait(string $task_data, float $timeout = 0.5, int $dst_worker_id = -1);
Returns
the result of the execution of the :task
Description of the parameters:
Parameters | Description |
---|---|
string data | Task data |
float timeout | Time-out time |
int dst_worker_id | Specify which task process to post to, which is random by default |
Description:
Taskwait has the same function as the task method, which is used to post an asynchronous task to the task process pool.
Unlike task, taskwait is blocked waiting until the task is completed or timed back.
Once the task is complete, you can return the results directly through the return
Example :
$task_id = $serv->taskwait("some data", 30);
Feature Description:
Pass Task result data to the worker process
Function prototype:
// 类成员函数
public function swoole_server::finish(string $task_data);
Back
: None
Description of the parameters:
Parameters | Description |
---|---|
string data | Results data |
Description:
Using swoole_server: The finish function must set the
onFinish callback function
for the server.
This function is only available in the
onTask callback of the
Task Worker process
swoole_server: finish is optional.
If the Worker process does not care about the results of task execution, you can not call this function
This function has been discarded in versions above swoole-1.7.2 and is replaced by return.
Example
:
$serv->finish("result data");
Function Description:
Heartbeat testing
Function prototype:
// 类成员函数
public function swoole_server::heartbeat(bool $if_close_connection = true);
Back
: None
Description of the parameters:
Parameters | Description |
---|---|
bool if_close_connection | Whether to close the time-out connection defaults to true |
Description:
The function initiates a detection, traverses all connections, and
finds those connections that
are idle based on
the heartbeat_check_interval
and heartbeat_idle_time parameters set
By default, swoole closes these connections directly, and heartbeat returns the fd of those connections
If if_close_connection is false, heartbeat returns the fds for these idle connections, but does not close them
if_close_connection parameters are available in versions above swoole-1.7.4
Example
:
$serv->heartbeat();
Feature Description:
Get mysqli's socket file descriptor
Function prototype:
// 公共函数
int swoole_get_mysqli_sock(mysqli $db)
Returns
the fd of :mysqli
Description of the parameters:
Parameters | Description |
---|---|
mysqli db | Mysqli connection |
Description:
You can add mysql's socket to swoole to perform asynchronous MySQL queries.
If you want to use asynchronous MySQL, you need to make it when compiling swoole --enable-async-mysql
swoole_get_mysqli_sock only support mysqlnd drivers
Even asynchronous MySQL requires a connection pool, and a single SQL must have 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();
});
Feature Description:
The name of the setup process
Function prototype:
// 公共函数
void swoole_set_process_name(string $name);
Back
: None
Description of the parameters:
Parameters | Description |
---|---|
string name | The name of the process |
Description:
After you modify the process name, what you see through the ps command is no longer your_file.php php, but a set string
The swoole_server_create process name onStart is modified to the worker process name when the main process name is modified when the process name is changed to the worker process name before the process is changed
swoole_set_process_name compatibility issues, priority is given to phAP's built-in cli_set_process_title functions
Example
:
woole_set_process_name("swoole server");
Feature Description:
Get the version number of the swoole extension
Function prototype:
// 公共函数
string swoole_version();
Returns
the version number of the :swoole extension
Parameter Description:
None
Description:
Example
:
echo swoole_version();
Feature Description:
Converts the standard Unix Errno error code into an error message
Function prototype:
// 公共函数
string swoole_strerror(int $errno);
Returns:
An error message after conversion
Description of the parameters:
Parameters | Description |
---|---|
int errno | errno error code |
Description:
Example
:
echo swoole_strerror( $errno );
Feature Description:
Gets the error code for the most recent system call
Function prototype:
// 公共函数
int swoole_errno();
Returns:
The error code for the last system call
Parameter Description:
None
Description:
The value of the error code is related to the operating system.
However, using swoole_strerror to convert the error to an error message.
Example
:
echo swoole_strerror(swoole_errno());
Feature Description:
This function is used to get the IP address of all network interfaces on this machine
Function prototype:
// 公共函数
array swoole_get_local_ip();
Returns:
An associated array with the interface name key
Parameter Description:
None
Description:
Currently only IPv4 addresses are returned, and the return result filters out the local loop address 127.0.0.1
Returns the result sample array ("eth0"; "192.168.1.100");
:
var_dump(swoole_get_local_ip());