Swoole server configuration

backlog

The number of listen queue.

The configuration is an integer representing the number of pending connections that waits for accept.

buffer_output_size

Set the output buffer size in the memory.

The default value is 2M. The data to send can't be larger than buffer_output_size every times.

Usage

$server->set([
    'buffer_output_size' => 32 * 1024 *1024, // byte in unit
])

chroot

Redirect the root path of worker process.

This configuration is to separate the operation to the file system in the worker process from the real file system.

Usage

$serv->set(array('chroot' => '/data/server/'));

cpu_affinity_ignore

Set the cpu core number to handle the interrupt.

Usage

array('cpu_affinity_ignore' => array(0, 1))

daemonize

Daemonize the swoole server process.

If the value of daemonize is more than 1, the swoole server will be daemonized.

The program which wants to run long time must enable this configuration.

If the daemonize has been enabled, the standard output and error of the program will be redirected to logfile. And if the configuration of log_file hasn't been setted, the standard output and error of the program will be redirected to /dev/null.

After daemonizing the processes, the value of CWD will change and the relative path of file will be different. So it must use absolute path in the program.

discard_timeout_request

If the configuration of dispatch_mode is 1 or 3, there may be some data that arrive to worker process after closing the connection.

In this situation, if discard_timeout_request is true, the worker process will discard these data or still procee these data.

dispatch_func

Set the dispatch_func to dispatch the connection to the worker process.

The swoole server provides [five types of dispatch_mode. If the dispatch_mode can't meet your need, you can write C++ function or PHP function to realize customized dispatch strategy.

Usage

<?php
$serv->set(array(
    'dispatch_func' => 'my_dispatch_function',
));

Once the dispatch_func has been setted, the configuration dispatch_mode would not work.

If the function setted by dispatch_func, the swoole will result in a fatal error.

If the data dispatched is more than 8K, dispatch_func can get 0-8180 bytes data.

PHP function

It is forbidden to add any blocking operation in the dispatch_func otherwise the Reactor group would stop.

<?php
$serv->set(array(
    'dispatch_func' => function ($serv, $fd, $type, $data) {
        var_dump($fd, $type, $data);
        return intval($data[0]);
    },
));

Parameters:

Return:

the return must be a integer between 0 and worker_num

C++ function

In other extension, use swoole_add_function to register function to swoole

int dispatch_function(swServer *serv, swConnection *conn, swEventData *data);

int dispatch_function(swServer *serv, swConnection *conn, swEventData *data)
{
    printf("cpp, type=%d, size=%d\n", data->info.type, data->info.len);
    return data->info.len % serv->worker_num;
}

int register_dispatch_function(swModule *module)
{
    swoole_add_function("my_dispatch_function", (void *) dispatch_function);
}

dispatch_mode

The mode of dispatching connections to worker process.

This parameter only works for the SWOOLE_PROCESS mode swoole_server.

Usage advice

If the dispatch_mode is 1 or 3, the event of connect and close will be shielded.

enable_delay_receive

Enable the delay of receiving new connection.

Once enabled, the client which has been accepted would not be added to the EventLoop automaticlly and only trigger the callback function of the receive event.

The worker process needs to call $serv->confirm($fd) to confirm the connection manually and add the connection to the EventLoop.

Usage

<?php
// enable `enable_delay_receive`
$serv->set(array(
    'enable_delay_receive' => true,
));

$serv->on("Connect", function ($serv, $fd, $reactorId) {
    $serv->after(2000, function() use ($serv, $fd) {
        // confirm connection and start process data
        $serv->confirm($fd);
    });
});

enable_reuse_port

Enable the reuse of port.

enable_unsafe_event

Enable the event of close and close when the dispatch_mode is 1 or 3.

group

Set the group of worker and task worker process.

Usage

<?php
$serv->set(array('group' => 'www-data'));

heartbeat_check_interval

This configuration heartbeat_check_interval is the interval of polling every TCP connection.

If the connection hasn't sent any data to the server in the last interval of heartbeat_check_interval, the connection will be closed.

The swoole server would not send the heartbeat packet to the client but only wait for the heartbeat packet from the client. The heartbeat check of swoole server only check the last time of sending data from the client. If the time exceeds heartbeat_check_interval, the connection between the server and the client will be closed.

heartbeat_idle_time

This configuration which works with the heartbeat_check_interval stands for the max idle time of connection.

Usage

<?php
array(
    'heartbeat_idle_time' => 600,
    'heartbeat_check_interval' => 60,
);

log_file

Set the log path of swoole.

Tips

In the log file, there are some labels to distinguish the thread or process that output the log item.

Reopen the log file

If the log file has been mv or unlink, the log can't be recorded normally. In this situation, you can send SIGRTMIN

log_level

Set the level of log.

The log that is inferior to the log_level setted will not be recorded to log file.

Usage

<?php
$serv->set(array(
    'log_level' => 1,
));

Log level list

0 =>DEBUG // all the levels of log will be recorded
1 =>TRACE
2 =>INFO
3 =>NOTICE
4 =>WARNING
5 =>ERROR

max_conn

The max number of connection the server could handle at the same time.

After exceed this limit, the swoole server will refuse the new coming connection.

max_conn should be less than ulimit -n max_conn should be more than (serv->worker_num + SwooleG.task_worker_num) * 2 + 32 the default value of max_conn is ulimit -n the value of max_conn should not be too large and be setted according to the memory usage of server.

max_request

the number of max request the worker process could receive.

The dafault value of max_request is 0 which means there is no limit of the max request. If the max_request is setted to some number, the worker process will exit and release all the memory amd resouce occupied by this process after receiving the max_request request. And then, the manager will respawn a new worker process.

This parameter is to resolve the problem of nonlocalizable and slow memory leak.

max_request only works for synchronous, blocking and stateless reponse program The totally asynchronous server should not set max_request max_request only works for SWOOLE_PROCESS mode.

<?php
$serv = new swoole_server("127.0.0.1", 9501);
$serv->set(array(
            'worker_num' => 2,    
            'max_request' => 3,  
            'dispatch_mode'=>3,
));

$serv->on('receive', function ($serv, $fd, $from_id, $data) {
        $serv->send($fd, "Server: ".$data);
});

$serv->start();

Check the pid of worker process before request and after many times request.

message_queue_key

Set the key of message queue.

This configuration only works if the configuration of task_ipc_mode has been setted to 2 or 3.

The default value of message_queue_key is calculated by ftok($php_script_file, 1).

open_cpu_affinity

Open the affinity setting of cpu.

open_eof_check

This configuration is to check the package eof. The package eof is setted by the configuration package_eof

Usage

If this configuration has been enabled, the swoole will check the end of data from the client. If the end of data from client is the string setted by package_eof, the swoole will send the data to the worker process otherwise the swoole will continue receive and joint the data from client.

array(
    'open_eof_check' => true,
    'package_eof' => "\r\n", 
)

The above configuration example can be used for Memcache or POP protocal which ends by \r\n. Once setted, the worker process will receive one or serveral whole packages. In the worker process, you should use explode("\r\n", $data) split the data or set the configuration package_eof to split the data automatically.

open_eof_split

Enable the split of data to package.

Once the configuration open_eof_check has been setted, the worker process will receive the data ending with the specified string. This data may contain one or serval whole package. In this situation, you can enable the open_eof_split to split the data to package automatically. And then the callback function onReceive will receive a whole package.

open_http2_protocol

Enable the process of http2 protocal.

This configuration needs to compile swoole with --enable-http2

Usage

$serv->set(array('open_http2_protocol' => true));

open_http_protocol

Enable the process of http protocal.

Once this configuration has enabled, the callback function onReceive will receive a whole http package.

The swoole_http_server will enable this configuration automatically.

Usage

<?php
$serv->set(array('open_http_protocol' => true));

open_length_check

Open the check of package length.

If this configuration has enabled, the swoole will open the analysis of package which has fixed header and body. And the worker process will receive a whole package in the callback function onReceive.

This configuration should work with three other configurations.

package_length_type

Use some field in the header of package to stand for the length the package. The swoole supports 10 types of length. Check the full list in the configuration of package_length_type

package_body_offset

The offset of the package to calculate the length of package.

package_length_offset

The offset of value of length in the header

Example
struct
{
    uint32_t type;
    uint32_t uid;
    uint32_t length;
    uint32_t serid;
    char body[0];
}

The configuration designed from the above protocal design

<?php
$server->set(array(
    'open_length_check' => true,
    'package_max_length' => 81920,
    'package_length_type' => 'N',
    'package_length_offset' => 8,
    'package_body_offset' => 16,
));

open_mqtt_protocol

Enable the process of mqtt protocal.

Once this configuration has enabled, the swoole will analyze the mqtt package head and the callback function onReceive will receive a whole mqtt package.

Usage

<?php
$serv->set(array('open_mqtt_protocol' => true));

open_tcp_nodelay

Open this configuration to close the Nagle algorithm.

open_websocket_protocol

Enable the process of websocket protocal.

The swoole will enable this configuration open_http_protocol automatically if the configuration open_websocket_protocol has been enabled.

The swoole_websocket_server will enable this configuration automatically.

Usage

<?php
$serv->set(array('open_websocket_protocol' => true));

package_eof

Set the end string of package.

This configuration should work with open_eof_check.

The max length of this string is 8 bytes.

package_length_func

Set the function to check the length of package. The swoole supports the PHP function and C++ function.

The function returns an integer.

PHP function

<?php
$serv = new swoole_server("127.0.0.1", 9501);

$serv->set(array(
    'open_length_check' => true,
    'dispatch_mode' => 1,
    'package_length_func' => function ($data) {
        if (strlen($data) < 8) {
            return 0;
        }
        $length = intval(trim(substr($data, 0, 8)));
        if ($length <= 0) {
            return -1;
        }

        return $length + 8;
    },
    'package_max_length' => 2000000,
));

$serv->on('receive', function (swoole_server $serv, $fd, $from_id, $data){
    var_dump($data);
    echo "#{$serv->worker_id}>> received length=" . strlen($data) . "\n";
});

$serv->start();

package_length_type

The type of length. For now, the swoole supports 10 types.

package_max_length

The max length of package whose unit is byte.

Once the configuration open_length_check/open_eof_check/open_http_protocol has enabled, the internal of swoole will joint the data received from the client amd the data stores in the memory before recevicing the whole package. So to limit the usage of memory, it should set the package_max_length.

pid_file

The file path which the master process id saves in.

Usage

<?php
$server->set(array(
    'pid_file' => __DIR__.'/server.pid',
));

The pid of master process saves in the pid_file after the swoole server starts. And this file is deleted after the swoole server stops normally.

pipe_buffer_size

Set the buffer size of pipe.

Usage

<?php
$server->set([
    'pipe_buffer_size' => 32 * 1024 *1024,
]);

reactor_num

the number of the reactor thread(for SWOOLE_BASE_MODE)

You can change the number of event processing thread in the master process.

To make full use of cpu, the default number of reactor_num is the number of core in cpu.

In general, the number of the reactor thread is between one and four times of cpu cores.

socket_buffer_size

Set the buffer size of socket.

This configuration is to set the max memory size of connection.

Usage

<?php
$server->set([
    'socket_buffer_size' => 128 * 1024 *1024,
])

ssl_cert_file

It must add --enable-openssl to the support for ssl when you compile the swoole

To enable ssl, it should set the file path of the cert file and the key file.

<?php
$server = new swoole_server("0.0.0.0", 9501, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);
$server->set(array(
    'ssl_cert_file' => __DIR__ . '/config/ssl.cert',
    'ssl_key_file' => __DIR__ . '/config/ssl.key',
));

Convert PEM to DER openssl x509 -in cert.crt -outform der -out cert.der Convert DER to PEM openssl x509 -in cert.crt -inform der -outform pem -out cert.pem

ssl_ciphers

Set the ssl_ciphers to change the default encryption algorithm of openssl. The default encryption algorithm of openssl is EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH

<?php
$server->on(array(
    'ssl_ciphers' => 'ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP', // the swoole use the default algorithm when the `ssl_ciphers` is empty
));

ssl_key_file

It must add --enable-openssl to the support for ssl when you compile the swoole

To enable ssl, it should set the file path of the cert file and the key file.

<?php
$server = new swoole_server("0.0.0.0", 9501, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);
$server->set(array(
    'ssl_cert_file' => __DIR__ . '/config/ssl.cert',
    'ssl_key_file' => __DIR__ . '/config/ssl.key',
));

Convert PEM to DER openssl x509 -in cert.crt -outform der -out cert.der Convert DER to PEM openssl x509 -in cert.crt -inform der -outform pem -out cert.pem

ssl_method

Set the algorithm of ssl. The algorithm of client and server must be same otherwise the handshake of websocket will fail. The default algorithm is SWOOLE_SSLv23_METHOD

<?php
$server->set(array(
    'ssl_method' => SWOOLE_SSLv3_CLIENT_METHOD, // this configuration is available for the swoole whose version is higher than 1.7.20
));

task_ipc_mode

Set the communication mode between the task worker process and worker process.

the difference between mode 2 and 3 : mode 2 supports the feature of sending task to a specified task worker process by $serv->task($data, $task_worker_id) while the mode 3 don't support to specify task worker process.

The message queue uses the memory queue provided by os to store the data.

If the configuration mssage_queue_key hasn't been seted, the message queue would use the private queue and this private queue would been deleted after the close of swoole server.

If the configuration mssage_queue_key has been seted, the data of message queue would not be deleted and the swoole server could get the data after restart.

Use ipcrm -q message_queue_id to delete the data of message queue

task_max_request

the max number of task the task worker process could handle.

After handling the number of task_max_request tasks, the task worker process will exit and release all the memory amd resouce occupied by this process. And then, the manager will respawn a new task worker process.

The dafault value of task_max_request is 0 which means there is no limit of the max task request.

task_tmpdir

Set the path of temporary task data.

If the data sended by task exceeds 8192 bytes, the swoole will use the temporary file to store the data.

The default of task_tmpdir is /tmp.

task_worker_num

the number of task worker process.

To enable this parameter, it needs to register the callback function of task event and finish event.

The task worker process is synchronous and blocking.

According to the speed of sending task and handling task, set a reasonable value of task_worker_num.

tcp_defer_accept

This configuration is to defer the tcp connection to trigger accept.

user

Set the user of worker and task worker process.

Usage

<?php
$serv->set(array('user' => 'apache'));

worker_num

The number of the worker process

If the code of logic is asynchronous and non-blocking, set the worker_num to the value from one times to four times of cpu cores. If the code of logic is synchronous and blocking, set the worker_num according to the consuming time of request and load of os.