TCP/UDP Server

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

The TCP/UDP Server provides you with the API to run TCP, UDP, Unix Socket asynchronous servers. It supports IPv4, IPv6, one Way, two Way SSL and TLS Encryption. It is simple and quick to get a full TCP/UDP server setup and you don't need to know the internal implementations, you only have to write your application business logic for each server event in the callback functions. You can use the OpenSwoole Server to conveniently create a TCP/UDP server from your PHP scripts, there is no requirement to use Nginx although it might be recommended to use a proxy pass through.

Notice: The Server API can only be used in PHP CLI mode

QuickStart

Create a TCP Server

<?php
$server = new OpenSwoole\Server("127.0.0.1", 9501, OpenSwoole\Server::SIMPLE_MODE, OpenSwoole\Constant::SOCK_TCP);

Set Configuration Settings

<?php
$server->set([
    'worker_num' => 4,   // The number of worker processes
    'daemonize' => true, // Whether to start as a daemon process
    'backlog' => 128,    // TCP backlog connection number
]);

Register callback functions

<?php
$server->on('connect', function() {
    // ...
});

$server->on('receive', function() {
    // ...
});

$server->on('close', function() {
    // ...
});

There are four types of callback functions

Start the server

<?php
$server->start();

Overview

Methods

Events

Server Reaction Events

Event Information

Server Attributes

Server Settings

When a OpenSwoole server starts, configured options set using OpenSwoole\Server->set() are saved to OpenSwoole\Server->setting. You can access the server configuration option values while the server is running.

For Example:

<?php
$server = new OpenSwoole\Server('127.0.0.1', 9501);
$server->set(['worker_num' => 4]);

echo $server->setting['worker_num'];

Master PID

Get the main process thread ID of the master process.

You can only access this object property from the event onStart and onWorkerStart callbacks.

For Example:

<?php
$server = new OpenSwoole\Server("127.0.0.1", 9501);

$server->on('start', function ($server)
{
    echo $server->master_pid;
});

$server->on('receive', function ($server, $fd, $reactor_id, $data)
{
    $server->send($fd, 'OpenSwoole: '.$data);
    $server->close($fd);
});

$server->start();

You can send a SIGTERM signal to this process to shutdown the server.

Manager PID

Get the server manager process thread ID.

You can get this ID when inside of the onStart and onWorkerStart event callbacks.

For Example:

<?php
$server = new OpenSwoole\Server("127.0.0.1", 9501);

$server->on('start', function ($server)
{
    echo $server->manager_pid;
});

$server->on('receive', function ($server, $fd, $reactor_id, $data)
{
    $server->send($fd, 'OpenSwoole: '.$data);
    $server->close($fd);
});

$server->start();

You can send a send SIGUSR1 to this process to reload the server application.

Worker and Task Worker ID

Get the current worker process thread ID and task worker ID.

For Example:

<?php
$server = new OpenSwoole\Server('127.0.0.1', 9501);

$server->set([
    'worker_num' => 8,
    'task_worker_num' => 4,
]);

$server->on('WorkerStart', function ($server, int $workerId)
{
    if($server->taskworker)
    {
        echo "Task worker ID:{$workerId}\n";
        echo "Task worker ID:{$server->worker_id}\n";
    }
    else
    {
        echo "Worker ID:{$workerId}\n";
        echo "Worker ID:{$server->worker_id}\n";
    }
});

$server->on('Receive', function ($server, $fd, $reactorId, $data)
{
    // ...
});

$server->on('Task', function ($server, $taskId, $reactorId, $data)
{
    // ...
});

$server->start();

The server class property and $workerId argument are the same, just different ways of accessing them. Worker process IDs will range from [0, $server->setting['worker_num']-1].

The task worker IDs will range from [$server->setting['worker_num'], $server->setting['worker_num'] + $server->setting['task_worker_num']].

Even after a worker process restart, the worker ID does not change.

Worker PID

Get the current worker operating system process thread ID, using posix_getpid() will return the same value.

<?php
OpenSwoole\Server->worker_pid: int

Taskworker Process Status

Determine if the current process is a task process. Useful to check if you are within a worker or task process.

<?php
OpenSwoole\Server->taskworker: bool

Return Values

  • true: Indicates that the current process is a task worker process
  • false: Indicates that the current process is a worker process

Server Connections

You can access all the currently connected client connections via the OpenSwoole\Server->connections iterator object. This iterator object should be used with a foreach loop and allows you to access all the currently connected client file descriptors ('fds`).

For Example:

<?php
foreach ($server->connections as $fd)
{
  var_dump($fd);
}

echo "Currently connected client connections: " . count($server->connections) . "\n";

This allows you to loop through all the TCP fd connections on the server. You can also use OpenSwoole\Server->getClientList() but this way is more recommended.

The server connections is not a PHP array, it is a iterator object, that is why a foreach is recommended to be used.

In OpenSwoole\Server::SIMPLE_MODE mode, it does not support cross-process operation TCP connections, so the BASE mode can only access the current process connections iterator, not the whole server like OpenSwoole\Server::POOL_MODE mode allows you to.

Server Ports

It is possible to setup a OpenSwoole server which listens on multiple ports. You can access which ports the server is listening on via OpenSwoole\Server->ports which is a class property and a collection of OpenSwoole\Server\Port objects of the current ports being used.

For Example:

<?php
$ports = $server->ports;

$ports[0]->set($settings);

$ports[1]->on('Receive', function()
{
    // ...
});

foreach ($server->ports as $port)
{
  var_dump($port);
}

Port zero is always the master port of the server.

Mime Helper Functions

Swoole provides you with some MIME helper functions to aid you when managing different MIME Types.

Since version 4.5.0

Mime Type Add

Definition:

function swoole_mime_type_add(string $suffix, string $mime_type): bool

Description:

Adds a new mime type to the built-in mime type table.

Mime Type Set

Definition:

function swoole_mime_type_set(string $suffix, string $mime_type): bool

Description:

Modify a mime type, fails if it does not exist and returns false.

Mime Type Delete

Definition:

function swoole_mime_type_delete(string $suffix): bool

Description:

Delete a mime type, fails if it does not exist and returns false.

Mime Type Get

Definition:

function swoole_mime_type_get(string $filename): string

Description:

Get the mime type corresponding to the file name.

Mime Type Exists

Definition:

function swoole_mime_type_exists(string $suffix): bool

Description:

Get whether the mime type corresponding to the suffix exists.

Last updated on September 20, 2022