DEV Community

Evgeniy Panov
Evgeniy Panov

Posted on

Swoole: an asynchronous framework for PHP

Swoole - PHP on steroids

Swoole is a high-performance extension for PHP that radically changes the approach to server application development. Unlike the classic PHP-FPM model, Swoole implements asynchronous I/O processing, uses coroutines, and provides built-in support for WebSocket and various network protocols.

Installation options

Swoole is distributed through the PECL repository. To get started, you will need to install the basic components:

sudo apt update
sudo apt install php php-dev php-pear
Enter fullscreen mode Exit fullscreen mode

After completing the installation, you need to add the line extension=openswoole.so to the php.ini configuration file.
An alternative method is to use Composer:

composer require openswoole/core
Enter fullscreen mode Exit fullscreen mode

Docker is suitable for an isolated development environment. You can use a ready-made PHP image with Swoole or create your own using Dockerfile:

FROM php:7.4-cli
RUN pecl install openswoole && docker-php-ext-enable openswoole
Enter fullscreen mode Exit fullscreen mode

Assembling and launching the container:

docker build -t php-swoole .
docker run -p 9501:9501 -v $(pwd):/app -w /app php-swoole php your-script.php
Enter fullscreen mode Exit fullscreen mode

Swoole Architecture

Swoole is built on a multi-process architecture with a clear separation of duties.

The master process coordinates the work of the entire system. It spawns reactor threads to handle networking, launches the process manager, and handles system signals.

Reactor threads run inside the master process and manage network connections. Using epoll or kqueue mechanisms, they asynchronously receive data from clients and send it for processing.

The process manager monitors the lifecycle of worker processes, controls their status, and restarts them if necessary.

Workers execute the main business logic of the application. They receive requests through reactor threads, process them, and generate responses.

Task Workers are designed to perform heavy operations that can block the main thread: lengthy calculations, calls to external APIs, and other resource-intensive tasks.

Request lifecycle:

  1. A client request arrives at the main process's reactor thread
  2. The reactor thread passes the data to a worker process
  3. The worker process either handles the request itself or delegates tasks to task workers
  4. The result is returned to the client via the reactor thread

Syntax basics

Creating an HTTP server begins with initializing an instance of OpenSwoole\HTTP\Server. Event handling is implemented through the on method, and sending a response is implemented through the end method of the Response object:

$server = new OpenSwoole\HTTP\Server("127.0.0.1", 9501);
$server->on("request", function ($request, $response) {
    $response->end("Hello World\n");
});
$server->start();
Enter fullscreen mode Exit fullscreen mode

Coroutines are used for asynchronous programming, which are launched by the go or co::run functions.
WebSocket servers are configured similarly to HTTP servers with open, message, and close event handling.
The configuration of task processes looks like this:

$server->set(['task_worker_num' => 4]);
$server->on('task', function ($server, $taskId, $data) {
    // task processing logic
});

$server->on('finish', function ($server, $taskId, $returnValue) {
    // actions after completion
});
Enter fullscreen mode Exit fullscreen mode

TCP/UDP servers and clients
The OpenSwoole\Server class is used to create TCP/UDP servers. Parameters are configured using the set method:

$server = new OpenSwoole\Server("127.0.0.1", 9501);
$server->set(['worker_num' => 4]);
$server->on('receive', function ($server, $fd, $reactor_id, $data) {
    $server->send($fd, 'Received: '.$data);
    $server->close($fd);
});
$server->start();
Enter fullscreen mode Exit fullscreen mode

The OpenSwoole\Coroutine\Client class is used for client connections, providing non-blocking network operations:

use OpenSwoole\Coroutine\Client;

co::run(function() {
    $client = new Client(SWOOLE_SOCK_TCP);
    if (!$client->connect('127.0.0.1', 9501, 0.5)) {
        echo "Connection failed: {$client->errCode}\n";
    }
    $client->send("Hello World\n");
    echo $client->recv();
    $client->close();
});
Enter fullscreen mode Exit fullscreen mode

HTTP and WebSocket with coroutines

An HTTP server is created using the OpenSwoole\HTTP\Server class. Coroutines allow multiple requests to be processed in parallel without blocking:

use OpenSwoole\HTTP\Server;
use OpenSwoole\Http\Request;
use OpenSwoole\Http\Response;

$server = new Server("0.0.0.0", 9501);
$server->on("request", function (Request $request, Response $response) {
    $response->end("Hello, Swoole HTTP!");
});
$server->start();
Enter fullscreen mode Exit fullscreen mode

The WebSocket server provides bidirectional communication via TCP. The open, message, and close events allow you to control the entire connection lifecycle:

use OpenSwoole\WebSocket\Server;
use OpenSwoole\Http\Request;
use OpenSwoole\WebSocket\Frame;

$server = new Server("0.0.0.0", 9502);
$server->on("open", function (Server $server, Request $request) {
    echo "New connection:  {$request->fd}\n";
});
$server->on("message", function (Server $server, Frame $frame) {
    echo "Message received:  {$frame->data}\n";
    $server->push($frame->fd, "echo: {$frame->data}");
});
$server->on("close", function ($ser, $fd) {
    echo "Connection closed: {$fd}\n";
});
$server->start();
Enter fullscreen mode Exit fullscreen mode

Practical examples

A WebSocket server with routing and SSL support demonstrates Swoole's capabilities for creating secure real-time applications. Routing allows you to separate the logic for processing different types of requests, while SSL provides traffic encryption.
An HTTP server with a routing system and validation shows how to implement a REST API with authentication and processing of various HTTP methods.
Detailed documentation and additional examples are available on the official project website.

Top comments (0)