Boost PHP Performance with Workerman’s Asynchronous HTTP Client

Workerman/http-client is a high‑performance, asynchronous PHP HTTP client that follows PSR‑7, includes a built‑in connection pool, supports multiple protocols, and can be installed via Composer; the guide shows installation steps, coroutine usage, concurrent request examples, and integration with Webman.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
Boost PHP Performance with Workerman’s Asynchronous HTTP Client

Overview

workerman/http-client is an asynchronous HTTP client component for PHP. All requests and responses are non‑blocking, it ships with a built‑in connection pool, and its messages conform to the PSR‑7 standard.

Features

Asynchronous non‑blocking : Requests and responses run asynchronously without blocking the main thread, allowing multiple HTTP operations in parallel.

Built‑in connection pool : Reuses TCP connections to reduce overhead of establishing and closing sockets.

PSR‑7 compliance : Enables seamless integration with other PSR‑7 compatible PHP libraries.

Multi‑protocol support : Besides HTTP/HTTPS, it also supports WebSocket, WSS, and other protocols.

Installation

composer require workerman/http-client
Note : Coroutine usage requires workerman>=5.0 and workerman/http-client>=2.0.0 . Additionally install the event‑loop library: <code>composer require revolt/event-loop ^1.0.0</code>

Starting Webman

/var/www/webman/admin.webman.tinywan.com # php start.php start

The command launches Workerman in DEBUG mode and shows worker and connection details.

Coroutine Usage in Workerman

Basic Example

declare(strict_types=1);
use Workerman\Worker;

require_once '../vendor/autoload.php';

try {
    $worker = new Worker();
    $worker->onWorkerStart = function () {
        $http = new Workerman\Http\Client();

        $response = $http->get('https://www.tinywan.com/');
        var_dump($response->getStatusCode());
        echo $response->getBody() . PHP_EOL;

        $response = $http->post('https://www.tinywan.com/', ['key1' => 'value1', 'key2' => 'value2']);
        var_dump($response->getStatusCode());
        echo $response->getBody() . PHP_EOL;

        $response = $http->request('https://www.tinywan.com/', [
            'method'  => 'GET',
            'version' => '1.1',
            'headers' => ['Connection' => 'keep-alive'],
            'data'    => ['key1' => 'value1', 'key2' => 'value2'],
        ]);
        echo $response->getBody() . PHP_EOL;
    };
    Worker::runAll();
} catch (Throwable $throwable) {
    var_dump($throwable->getMessage());
}

Asynchronous Concurrent Requests

<?php
/**
 * @desc Pseudo‑code example
 * @author Tinywan (ShaoBo Wan)
 */
declare(strict_types=1);

use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;

require_once '../vendor/autoload.php';

$httpWorker = new Worker("http://0.0.0.0:8217");
$httpWorker->count = 8;

$httpWorker->onMessage = function (TcpConnection $connection, Request $request) {
    $http = new \Workerman\Http\Client();
    $count = 50;
    $result = [];
    while ($count--) {
        $startTime = microtime(true);
        echo '开始时间:' . $startTime . PHP_EOL;
        $response = $http->get('https://api.tinywan.com/systems/website');
        $endTime = microtime(true);
        echo '结束时间:' . $endTime . PHP_EOL;
        $result[] = sprintf('第%d个  | 耗时%s秒 | 状态码%d', $count, $endTime - $startTime, $response->getStatusCode());
    }
    $connection->send(json_encode($result));
};

Worker::runAll();

Using the Client Inside Webman

If you need to perform asynchronous HTTP requests within a Webman application and stream the result back to the frontend, the following controller demonstrates the pattern.

declare(strict_types=1);

namespace app\controller;

use support\Request;
use support\Response;
use Throwable;
use Workerman\Protocols\Http\Chunk;

class CoroutineController
{
    /**
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function index(Request $request): Response
    {
        $connection = $request->connection;
        $http = new \Workerman\Http\Client();
        $http->get('https://api.tinywan.com/website', function ($response) use ($connection) {
            $connection->send(new Chunk($response->getBody()->getContents()));
            $connection->send(new Chunk('')); // empty chunk signals end of response
        });
        return response()->withHeaders([
            "Transfer-Encoding" => "chunked",
            "Access-Control-Allow-Origin" => "*",
        ]);
    }
}

The controller sends a Transfer-Encoding: chunked header, streams the HTTP body in chunks, and finally sends an empty chunk to indicate completion.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPWebmanWorkermanPSR-7Async HTTP
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.