Coroutine TCP Server: Multi Process Server Example


This example shows you how to use the coroutine TCP server with the process module from Swoole. By using the multi process module you can setup a multi process TCP server which you can manage.



use Swoole\Process;
use Swoole\Coroutine;
use Swoole\Coroutine\Server\Connection;

// We use a process pool to create a Multi-process management module
$pool = new Process\Pool(2);

// By enabling this, each callback to WorkerStart will automatically create a coroutine for you
$pool->set(['enable_coroutine' => true]);

// Creates a Co\run context for you because enable_coroutine = true...
$pool->on('WorkerStart', function($pool, $id)
    // Each process listens on port 9501
    $server = new Swoole\Coroutine\Server('', 9501, false, true);

    // Handle kill triggers when a SIGTERM is sent
    Process::signal(SIGTERM, function() use ($server)
        // This is how the server is stopped when a kill event is sent

    // Receive a new connection request and automatically create a coroutine context
    $server->handle(function(Connection $connection)
        // The Co\run context is created for you...

            // Receive data from the request
            $data = $connection->recv(1);

            // Handle empty data or false types
            if($data === '' || $data === false)
                // Either there is no data to process or there was an error
                $errCode = swoole_last_error();
                $errMsg = socket_strerror($errCode);
                echo "errCode: {$errCode}, errMsg: {$errMsg}\n";

                // Breaks the while loop

            // Send back data to the connect client

            // Delay the next loop by 1 second

    // Start the server and begin listening on port 9501

// Starting the pool means that WorkerStart is called...

This example shows you how to manage multiple coroutine focused servers over a range of multi-processes by using the Swoole Process Pool. You can increase the number of processes by changing $pool = new Process\Pool(2). The number 2 means that two processes will be executed and 2 servers will be able to process requests. Each coroutine server will listen on the same IP and Port, they basically compete to take requests and connect to the client.

You could easily make this example a single process server by using $pool = new Process\Pool(1).