Coroutine TCP Server

Experimental feature

Please use Swoole Server if no special requirements.

Swoole Coroutine Server which uses the TCP protocol and allows you to create a server within a coroutine context programmatically on the fly. It is a TCP server which uses UnixSockets for communication.

Multiple Coroutine Servers can be created within one process. Servers can be created and destroyed dynamically at runtime or throughout a script.

This TCP coroutine focused server is different and not a replacement of the Swoole\Server or Swoole\Http\Server classes that use event callbacks. This coroutine server can be used with Swoole\Process\Pool to manage its server events in a certain order like Connect, Receive and `Close.

The full namespace for this class is Swoole\Coroutine\Server but it also has a shorthand alias as well, which is Co\Server.

First available since version v4.4


Methods


Quick Start Example

<?php

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

Co\run(function()
{
    go(function()
    {
        $server = new Server('0.0.0.0', 9501, false);

        $server->handle(function(Connection $conn)
        {
            while(true)
            {
                $data = $conn->recv();
                if(!$data)
                {
                    break;
                }

                $conn->send("hello $data");
            }

            $conn->close();
        });

        echo "Start TCP server :9501\n";
        $server->start();
    });

    go(function()
    {
        $server = new Server('0.0.0.0', 9502, false);

        $server->handle(function(Connection $conn)
        {
            while(true)
            {
                $data = $conn->recv();
                if(!$data)
                {
                    break;
                }

                $conn->send("hello $data");
            }

            $conn->close();
        });

        echo "Start TCP server :9502\n";
        $server->start();
    });
});