What Is Workerman and How to Use Its Connection Class in PHP
Workerman is an open‑source, high‑performance PHP application container that provides a low‑level service framework for building TCP/UDP, WebSocket, HTTP, and custom protocol servers, and this guide explains its core concepts, the Worker and Connection classes, and a simple usage example with code.
What Is Workerman?
Workerman is an open‑source, high‑performance PHP application container. It is not an MVC framework but a lower‑level, generic service framework that can be used to develop TCP proxies, ladder proxies, game servers, mail servers, FTP servers, and even PHP implementations of Redis, databases, Nginx, or php‑fpm. By moving PHP beyond traditional web‑only use, Workerman represents an innovation in the PHP ecosystem.
Internally, Workerman resembles a PHP version of Nginx: it uses multiple processes, epoll, and non‑blocking I/O. Each process can maintain tens of thousands of concurrent connections. Because it runs as a resident process, it does not depend on Apache, Nginx, or php‑fpm, delivering extremely high performance. It supports TCP, UDP, UNIX socket, long‑living connections, WebSocket, HTTP, WSS, HTTPS, and custom protocols. It also provides timers, asynchronous socket clients, async Redis, async HTTP, and async message‑queue components.
What Is the Connection Class?
Workerman defines two key classes: Worker and Connection. Each client connection is represented by a Connection object, which offers callbacks such as onMessage and onClose, as well as methods like send() and close(). The Worker acts as a listener container that accepts client connections and wraps them into Connection objects for developer interaction.
Simple Usage Example
<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('http://0.0.0.0:8686');
$worker->onWorkerStart = function ($worker) {
// initialization code
};
$worker->onConnect = function ($connection) {
echo "connection success" . PHP_EOL;
};
$worker->onMessage = function (TcpConnection $connection, Request $request) {
$connection->send("hello");
};
$worker->onClose = function ($connection) {
echo "connection close" . PHP_EOL;
};
$worker->onWorkerStop = function ($worker) {
// cleanup code
};
// Run all workers
Worker::runAll();Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
