Introduction
Swoole is a parallel network communication engine based on asynchronous event-driven and coroutine written in C++ language, providing coroutine and high-performance network programming support for PHP. It provides a variety of network servers and client modules with communication protocols, which can easily and quickly implement TCP/UDP services, high-performance Web, WebSocket services, Internet of Things, real-time communications, games, microservices, etc., so that PHP is no longer limited to the traditional Web field.
PHP's asynchronous, parallel, and high-performance network communication engine is written in pure C language and provides asynchronous IO servers and clients with multiple communication protocols. Swoole4 supports the full Coroutine + Channel CSP programming mode, and can implement asynchronous programs using a synchronous style.
Predefined constants
// Predefined constantsSWOOLE_VERSION currentSwooleVersion number,String type,like1.6.0 // swoole_server constructor parameterSWOOLE_BASE useBasemodel,The business code isReactorExecute directly in the process SWOOLE_PROCESS use进程model,The business code isWorkerExecute in process // swoole_client constructor parameterSWOOLE_SOCK_TCP createtcp socket SWOOLE_SOCK_TCP6 createtcp ipv6 socket SWOOLE_SOCK_UDP createudp socket SWOOLE_SOCK_UDP6 createudp ipv6 socket SWOOLE_SOCK_SYNC Synchronize the client SWOOLE_SOCK_ASYNC Asynchronous client // swoole_lock constructor parameterSWOOLE_FILELOCK create文件锁 SWOOLE_MUTEX create互斥锁 SWOOLE_RWLOCK create读写锁 SWOOLE_SPINLOCK create自旋锁 SWOOLE_SEM create信号量 // SSL encryption methodSWOOLE_SSLv3_SERVER_METHOD; SWOOLE_SSLv3_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;
Server Configuration Options
$serv->set(array( // Use this parameter to adjust the number of event processing threads in the main process to make full use of multi-cores. By default, the same number of CPU cores will be enabled. Generally set to 1-4 times the number of CPU cores 'reactor_num' => 2, // Set the number of Worker processes to be started. The business code is fully asynchronous and non-blocking, and it is most reasonable to set it to 1-4 times the CPU. // The business code is synchronous blocking, and needs to be adjusted according to the request response time and system load 'worker_num' => 2, // Set the maximum number of tasks in the worker process, the default is 0. A worker process will automatically exit after processing tasks exceeding this value. After the process exits, all memory and resources will be released. 'max_request' => 1000, // Server program, maximum allowed number of connections, this parameter is used to set the maximum number of TCP connections allowed by the server. After this number exceeds, newly entered connections will be denied 'max_connection' => 10000, // Configure the number of Task processes. After configuring this parameter, the task function will be enabled. So Server must register onTask 'task_worker_num' => 2, // Set the way to communicate between the Task process and the Worker process. 1. Use unix socket communication, default mode, 2. Use message queue communication, 3. Use message queue communication, and set to compete mode 'task_ipc_mode' => 1 // Set the maximum number of tasks in the task process. A task process will automatically exit after processing tasks exceeding this value. 'task_max_request' => 0, // Set the task's temporary data directory. In swoole_server, if the delivered data exceeds 8192 bytes, a temporary file will be enabled to save the data. 'task_tmpdir' => '/tmp', // The packet distribution strategy defaults to 2. 1 round-robin mode, 2 fixed mode, 3 preemption mode, 4IP allocation, 5UID allocation 'dispatch_mode' => 2, // Set the dispatch function. Swoole has built-in 5 types of dispatch_modes under the bottom layer. If the requirements are still not met. // You can use C++ or PHP functions to implement dispatch logic. How to use: 'dispatch_func' => 'my_dispatch_function', // Set the KEY of the message queue, only when task_ipc_mode = 2/3. // The set Key is only used as the KEY of the Task task queue. The default value of this parameter is ftok($php_script_file, 1) 'message_queue_key' => ftok(SYS_ROOT . '', 1), // Set daemon mode 'daemonize' => 1, // Listen queue length, such as backlog => 128, this parameter will determine at most how many connections waiting for accept are at the same time 'backlog' => 128, // Specify swoole error log file. Exception information that occurs during the swoole runtime will be recorded in this file. By default, it will print to the screen 'log_file' => '/data/logs/', // Set the level of swoole_server error log printing, the range is 0-5. Log information below log_level settings will not be thrown 'log_level' => 1, // Enable heartbeat detection, this option indicates how often the cycle is cycled in seconds 'heartbeat_check_interval' => 10, // Use with heartbeat_check_interval. Indicates the maximum allowable idle time for the connection 'heartbeat_idle_time' => 20, // Turn on EOF detection. This option will detect data sent by the client connection. It will only be delivered to the Worker process when the end of the data packet is the specified string. // Otherwise, the packet will be spliced until the cache area is exceeded or the timeout will not abort. When an error occurs, the underlying layer will consider it a malicious connection, discard the data and force the connection to be closed. 'open_eof_check' => true, // Enable EOF automatic subcontracting. After setting open_eof_check, the underlying layer detects whether the data is buffered with a specific string ending to the data 'open_eof_split' => true, // Use with open_eof_check or open_eof_split to set the EOF string. 'package_eof' => "\r\r\n", // Open the package length detection feature. Package length detection provides analysis of the format protocol of fixed package header + package body. // After enabled, it can ensure that the Worker process onReceive will receive a complete packet every time. 'open_length_check' => true, // The type of length value, accepts a character parameter, which is consistent with the pack function of php. 'package_length_type' => 'N', // Set length analysis function, supporting two types of functions in C++ or PHP. The length function must return an integer 'package_length_func' => 'package_length_func_name' // Set the maximum packet size in bytes 'package_max_length' => 2000000, // Enable CPU affinity settings 'open_cpu_affinity' => 1, // cpu_affinity_ignore setting to empty this CPU, specifically used to handle network interrupts 'cpu_affinity_ignore' => [0,1], // Enable open_tcp_nodelay. After opening, the TCP connection will close the Nagle merge algorithm when sending data, and send it to the client connection immediately. 'open_tcp_nodelay' => 1, // Enable the tcp_defer_accept feature, which can be set to a numeric value, indicating that accept is triggered when a TCP connection has data sent 'tcp_defer_accept' => 5 // Set SSL tunnel encryption, set the value to a file name string, and set the path to the cert certificate and key private key 'ssl_cert_file' => __DIR__.'/config/', 'ssl_key_file' => __DIR__.'/config/', // Set the OpenSSL tunnel encryption algorithm. The algorithm used by Server and Client must be consistent, otherwise the SSL/TLS handshake will fail and the connection will be cut off. 'ssl_method' => SWOOLE_SSLv3_CLIENT_METHOD, // After SSL is enabled, set ssl_ciphers to change the default encryption algorithm of openssl 'ssl_ciphers' => 'ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP', // Set the user to which the worker/task child process belongs 'user' => 'swoole', // Set the process user group of the worker/task child process 'group' => 'www-data', // Redirect the file system root directory of the Worker process 'chroot' => '/data/server/', // Automatically write the PID of the master process to the file when the server is started, and automatically delete the PID file when the server is closed 'pid_file' => __DIR__.'/', // Adjust the memory buffer length of pipeline communication. Swoole uses Unix Socket to implement inter-process communication. 'pipe_buffer_size' => 32 * 1024 *1024, // Configure the memory size of the send output buffer area 'buffer_output_size' => 32 * 1024 *1024 // Configure the cache area length of the client connection 'socket_buffer_size' => 128 * 1024 *1024 // After swoole configures dispatch_mode=1 or 3, because the system cannot guarantee the order of onConnect/onReceive/onClose, the onConnect/onClose event is turned off by default. // If the application requires the onConnect/onClose event and can accept the security risks that may be caused by the order issue, // You can enable onConnect/onClose events by setting enable_unsafe_event to true 'enable_unsafe_event' => true, // After swoole configures dispatch_mode=1 or 3, the system cannot guarantee the order of onConnect/onReceive/onClose, so some request data may be required after the connection is closed. // Only then can you reach the Worker process. The discard_timeout_request configuration defaults to true, indicating that if the worker process receives a data request for a closed connection, it will be automatically discarded. // Discard_timeout_request If set to false, it means that the data request will be processed regardless of whether the connection is closed or not. 'discard_timeout_request' => true, // Set port reuse 'enable_reuse_port' => true, // After setting this option to true, the EventLoop will not be automatically added after the accept client connects, and only the onConnect callback is triggered. // The worker process can call $serv->confirm($fd) to confirm the connection, and then fd will be added to EventLoop to start data transmission and reception. // You can also call $serv->close($fd) to close this connection. 'enable_delay_receive' => true, // Enable Http protocol processing 'open_http_protocol' => true, // Enable HTTP2 protocol resolution, and you need to rely on the --enable-http2 compilation option. Default is false 'open_http2_protocol' => true, // Enable websocket protocol processing, Swoole\WebSocket\Server will automatically enable this option 'open_websocket_protocol' => true, // Enable mqtt protocol processing. After enabled, the mqtt package header will be parsed. The worker process onReceive will return a complete mqtt packet each time. 'open_mqtt_protocol' => true, // Set the asynchronous restart switch 'reload_async' => true, // Turn on TCP fast handshake feature. This feature can improve the response speed of TCP short connections, carry data when the client completes the third step of handshake when sending SYN packets 'tcp_fastopen' => true // Turn on the request slow log. After enabled, the Manager process will set a clock signal to detect all Task and Worker processes regularly. // Once the process blocks, the request exceeds the specified time, the process's PHP function call stack will be automatically printed 'request_slowlog_file' => '/tmp/', // enable_coroutine parameter, default is true, and the built-in coroutine can be turned off by setting it to false 'enable_coroutine' => false // Set the maximum number of coroutines in the current worker process. If the max_coroutine layer exceeds max_coroutine, the underlying layer will not be able to create a new coroutine. The underlying layer will throw an error and directly close the connection 'max_coroutine' => 3000, ));
Server function list
// Create an asynchronous Server object.$serv = new swoole_server('0.0.0.0', '9501', $mode = SWOOLE_PROCESS, $sock_type = SWOOLE_SOCK_TCP); // swoole_server->set function is used to set various parameters of swoole_server runtime. // After the server is started, access the parameter array set by the set function through $serv->setting.$serv->set(array( 'reactor_num' => 2, 'worker_num' => 4, 'backlog' => 128, 'max_request' => 50, 'dispatch_mode' => 1, )); // Register the Server's event callback function.$serv->on('connect', function ($serv, $fd){ echo "Client:Connect.\n"; }); // Add the listening port. In the business code, you can call swoole_server::connection_info to get which port a connection comes from.$serv->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP); // Listen to a new Server port, this method is an alias for addlistener$serv->listen("127.0.0.1", 9503, SWOOLE_SOCK_TCP); // Add a user-defined worker process. This function is usually used to create a special worker process for monitoring, reporting, or other special tasks.$process = new swoole_process(function($process) use ($server) { while (true) { $msg = $process->read(); foreach($server->connections as $conn) { $server->send($conn, $msg); } } }); $server->addProcess($process); // Start the server and listen to all TCP/UDP ports$serv->start(); // Restart all worker processes. $only_reload_taskworkrer Whether to restart the task process only$serv->reload($only_reload_taskworkrer = false); // Make the current worker process stop running and immediately trigger the onWorkerStop callback function.swoole_server->stop(int $worker_id = -1, bool $waitEvent = false); // This function can be used in the worker process. Sending SIGTERM to the main process can also enable shutdown of the server.$serv->shutdown(); // tick timer, you can customize callback functions. This function is an alias for swoole_timer_tick.$serv->tick(1000, function ($id) { var_dump($id); }); // Execute the function after the specified time. The swoole_server::after function is a one-time timer and will be destroyed after execution is completed.$serv->after(2000, function(){ echo "Timeout: ".microtime(true)."\n"; }); // Delay execution of a PHP function. The Swoole underlying layer will execute this function after the EventLoop loop is completed. // The purpose of this function is to delay execution of some PHP code, and the program prioritizes IO events.$server->defer(function() use ($db) { $db->close(); }); // Clear the tick/after timer, this function is an alias for swoole_timer_clear.$timer_id = $server->tick(1000, function ($id) use ($server) { $server->clearTimer($id); }); // Close the client connection, the operation returns true for success, and false for failure.$serv->close($fd); // Send data to the client $data. The maximum data sent. The TCP protocol must not exceed 2M. You can modify buffer_output_size to change the maximum packet length allowed to be sent. // UDP protocol shall not exceed 65507, UDP header accounts for 8 bytes, IP header accounts for 20 bytes, 65535-28 = 65507$serv->send($fd, 'Swoole: '.$data); // Send files to TCP client connection$serv->sendfile($fd, __DIR__.'/'); // Send UDP packets to any client IP:PORT$serv->sendto("127.0.0.1", 9999, "hello world"); // Send data to the client blockingserver->sendwait($fd, "hello world"); // This function can send messages to any worker process or task process. Callable in non-main and administrative processes. The process that receives the message will trigger the onPipeMessage event$serv->sendMessage("hello task process", $worker_id); // Check whether the connection corresponding to fd exists. The TCP connection corresponding to $fd returns true, and the non-existence returns false$serv->exist($fd) // Stop receiving data. After calling this function, the connection will be removed from EventLoop and no longer receives client data.$serv->pause($fd) // Recover data reception. Use it in pairs with the pause method. After calling this function, the connection will be re-added to EventLoop and continue to receive client data.$serv->resume(int $fd); // swoole_server->getClientInfo function is used to obtain connection information, the alias is swoole_server->connection_info$fdinfo = $serv->connection_info($fd); // Used to traverse all client connections of the current server. The method is based on shared memory and does not exist. // It is recommended to use the swoole_server::$connections iterator to traverse the connection. The alias for getClientList is connection_list$conn_list = $serv->getClientList($start_fd, 10); // Bind the connection to a user-defined UID, you can set the dispatch_mode=5 setting to perform hash fixed assignment with this value. // It can be guaranteed that all connections to a certain UID will be assigned to the same Worker process.$serv->bind($fd, $uid) // Get the current server's active TCP connections, startup time, total number of accpet/close, and other information.$serv_stats = $serv->stats(); // Deliver an asynchronous task into the task_worker pool. This function is non-blocking and will be returned immediately after execution. The Worker process can continue to process new requests. // Using the Task function, task_worker_num must be set first, and the server's onTask and onFinish event callback functions must be set.$task_id = $serv->task("some data"); // taskwait works the same as task method, and is used to deliver an asynchronous task to the task process pool for execution. // Unlike task, taskwait is waiting synchronously until the task is completed or timed out.$serv->taskwait(['type' => 'array', 'value' => $data]); // Concurrent execution of multiple tasks, $tasks must be a numeric index array, and associative index arrays are not supported$tasks[] = mt_rand(1000, 9999); // Mission 1$tasks[] = mt_rand(1000, 9999); // Mission 2var_dump($tasks); // Wait for all Task results to return, timeout is 10s$results = $serv->taskWaitMulti($tasks, 10.0); // Concurrently execute task and perform coroutine scheduling$result = $serv->taskCo($tasks, 0.5); // This function is used to notify the worker process in the task process that the delivered task has been completed. This function can pass the result data to the worker process.$serv->finish("response"); // Detect all connections on the server and find connections that have exceeded the agreed time. // If if_close_connection is specified, the timeout connection will be automatically closed. Not specified to return only the fd array of connections.$closeFdArr = $serv->heartbeat(); // Get the error code for the last operation error. Different logic can be executed in business code according to the error code type.$errCode = $serv->getLastError(); // Call this method to get the underlying socket handle, and the returned object is the sockets resource handle. // Rely on PHP sockets extension, and the --enable-sockets option needs to be enabled when compiling swoole$socket = $serv->getSocket(); // Set the client connection to the protection state and not cut off by the heartbeat thread.$serv->protect(int $fd, bool $value = 1); // Confirm the connection and use it with enable_delay_receive or wait_for_bind. When the client establishes a connection, it does not listen for readable events. // Only trigger the onConnect event callback to execute confirmation connection in the onConnect callback. Only then will the server listen for readable events and receive data from the client connection.$serv->confirm(int $fd);
Server attribute list
// The parameters set by the swoole_server::set() function will be saved to the swoole_server::$setting property. The value of the running parameter can be accessed in the callback function.echo $serv->setting['worker_num']; // Returns the PID of the current server main process. int $serv->master_pid; // Returns the PID of the current server management process. int $serv->manager_pid; // Get the number of the current Worker process, including the Task process. The Worker process number range is [0, worker_num] // The Task process number range is [worker_num, worker_num + task_worker_num] int $serv->worker_id; // Get the operating system process ID of the current Worker process. The return value is the same as posix_getpid(). int $serv->worker_pid; // Boolean type, true means that the current process is a Task worker process, false means that the current process is a Worker process bool $serv->taskworker; // TCP connection iterator can use foreach to traverse all current connections on the server. // The function of this property is consistent with swoole_server->connection_list, but is more friendly. The traversed element is a single connected fd. // Listen to the port array. If the server listens to multiple ports, you can traverse swoole_server::$ports to get all Swoole\Server\Port objects. // where swoole_server::$ports[0] is the main server port set by the constructor.$ports = swoole_server::$ports; $ports[0]->set($settings); $ports[1]->on("Receive", function(){});
Event callback function
// Server starts the main thread of the main process to callback this function$serv->on('Start', function(Swoole\Server $server){}); // This event occurs when the server ends normally$serv->on('Shutdown', function(Swoole\Server $server){}); // This event occurs when the Worker process/Task process is started$serv->on('WorkerStart', function(Swoole\Server $server, int $worker_id){}); // This event occurs when the worker process terminates$serv->on('WorkerStop', function(Swoole\Server $server, int $worker_id){}); // Only after the reload_async feature is enabled, a new Worker process will be created to process the new request first, and the old Worker process will exit on its own.$serv->on('WorkerExit', function(Swoole\Server $server, int $worker_id){}); // When a new connection is entered, callback in the worker process$serv->on('Connect', function(Swoole\Server $server, int $fd, int $reactorId){}); // Callback this function when data is received, which occurs in the worker process$serv->on('Receive', function(Swoole\Server $server, int $fd, int $reactor_id, string $data){}); // Callback this function when receiving UDP packets, which occurs in the worker process$serv->on('Packet', function(Swoole\Server $server, string $data, array $client_info){}); // After the TCP client connection is closed, call back this function in the worker process$serv->on('Close', function(Swoole\Server $server, int $fd, int $reactorId){}); // This event is triggered when the buffer zone reaches the highest water level.$serv->on('BufferFull', function(Swoole\Server $serv, int $fd){}); // This event is triggered when the buffer area is below the lowest water level line$serv->on('BufferEmpty', function(Swoole\Server $serv, int $fd){}); // Called within the task_worker process. The worker process can use the swoole_server_task function to deliver new tasks to the task_worker process. // The current Task process will switch the process status to busy when calling the onTask callback function, and no new Task will be received. // When the onTask function returns, the process state will be switched to idle and then the new Task will continue to be received.$serv->on('Task', function(Swoole\Server $serv, int $task_id, int $src_worker_id, mixed $data){}); // When the task delivered by the worker process is completed in task_worker, // The task process will send the result of the task processing to the worker process through the swoole_server->finish() method$serv->on('Finish', function(Swoole\Server $serv, int $task_id, string $data){}); // The onPipeMessage event will be triggered when the worker receives a pipeline message sent by sendMessage. Both worker/task processes may trigger onPipeMessage events$serv->on('PipeMessage', function(Swoole\Server $server, int $src_worker_id, mixed $message){}); // When an exception occurs in the worker/task_worker process, this function will be called back in the Manager process.$serv->on('WorkerError', function(Swoole\Server $serv, int $worker_id, int $worker_pid, int $exit_code, int $signal){}); // Call it when the management process starts$serv->on('ManagerStart', function(Swoole\Server $serv){}); // Call it when the management process ends$serv->on('ManagerStop', function(Swoole\Server $serv){});