reusePort

Note
This feature requires workerman>= 3.2.1 and PHP>=7.0. It is not supported on Windows and Mac OS.

Description:

bool Worker::$reusePort

Sets whether the current worker enables socket port reuse (the SO_REUSEPORT option of the socket).

When port reuse is enabled, multiple unrelated processes are allowed to listen on the same port, and the system kernel performs load balancing to determine which process handles the socket connection, avoiding the thundering herd problem and improving the performance of multi-process short connection applications.

Note: This feature requires PHP version >=7.0.

Example 1

use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('websocket://0.0.0.0:8484');
$worker->count = 4;
$worker->reusePort = true;
$worker->onMessage = function(TcpConnection $connection, $data)
{
    $connection->send('ok');
};
// Run the worker
Worker::runAll();

Example 2: Workerman Multiple Port (Multi-Protocol) Listening

use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('text://0.0.0.0:2015');
$worker->count = 4;
// After each process starts, add a listener in the current process
$worker->onWorkerStart = function($worker)
{
    $inner_worker = new Worker('http://0.0.0.0:2016');
    /**
     * Multiple processes listen on the same port (the listening socket is not inherited from the parent process)
     * Port reuse must be enabled, otherwise, an Address already in use error will occur
     */
    $inner_worker->reusePort = true;
    $inner_worker->onMessage = 'on_message';
    // Execute listening
    $inner_worker->listen();
};

$worker->onMessage = 'on_message';

function on_message(TcpConnection $connection, $data)
{
    $connection->send("hello\n");
}

// Run the worker
Worker::runAll();