Building and Running Workerman Apps with ServBay
Overview
This document is designed to guide ServBay users on how to quickly set up and run high-performance asynchronous network applications based on Workerman in their local macOS or Windows development environment, utilizing ServBay's integrated PHP and Composer setup. Workerman is a powerful PHP library for creating network services that require high-concurrency processing, such as web servers, real-time communication servers, gaming servers, and more. ServBay provides a ready-to-use development platform that greatly simplifies Workerman's environment setup.
What Is Workerman?
Workerman is an open-source, high-performance asynchronous network communication framework written entirely in PHP. Built on the EventLoop model, it implements asynchronous non-blocking I/O and can efficiently handle large numbers of concurrent connections. Unlike traditional PHP web development models (such as Apache/Nginx + PHP-FPM), Workerman applications run as resident memory processes, listening to specific ports and directly managing network connections and data. This avoids the overhead of process destruction after each request in the traditional workflow and significantly improves performance and throughput.
With Workerman, you can easily build:
- High-performance HTTP servers, which can even replace Apache/Nginx for straightforward static or dynamic requests.
- Real-time WebSocket servers for applications like chat rooms and live data push.
- Custom protocol TCP/UDP servers.
- Command-line tools, scheduled tasks, microservices, and more.
Core Features and Advantages of Workerman
- High Performance: Core built on event-driven, asynchronous non-blocking I/O, capable of handling massive concurrent connections with outstanding performance.
- Multi-Protocol Support: Built-in support for HTTP, WebSocket, TCP, UDP, and flexible interfaces to implement custom protocols.
- Ease of Use: Simple and intuitive API reduces asynchronous network programming complexity, enabling PHP developers to get started quickly.
- Flexible Scalability: Supports a multi-process model for horizontal scaling and load balancing with multi-core CPUs. Easily integrates Composer packages and existing PHP libraries.
- PHP Ecosystem Integration: As a PHP library, it’s tightly integrated with the PHP ecosystem and can seamlessly use Composer for dependency management.
- Daemon Mode: Supports running as a background daemon for production deployment, ensuring service reliability and availability.
Workerman unlocks new possibilities for PHP developers to build high-performance, real-time, and highly concurrent network applications.
Setting Up the Workerman Development Environment with ServBay
ServBay is a local development environment tool crafted for web developers. It integrates runtimes for PHP, Node.js, Python, Go, Java, and more, as well as popular database and server software like Caddy, Nginx, Apache, MySQL, PostgreSQL, MongoDB, Redis, and Memcached. Its main advantage lies in its ready-to-use (zero-configuration) setup, especially with Composer pre-installed and configured, making Workerman project setup in ServBay fast and convenient.
This guide will walk you through building and running Workerman apps in ServBay via several basic examples—including a simple HTTP server, a WebSocket server, and a TCP server.
TIP
For better project management and consistency, ServBay recommends storing all local website projects in these directories:
- macOS:
/Applications/ServBay/www
- Windows:
C:\ServBay\www
All examples in this document use paths based on these directories.
Prerequisites
Before you begin, ensure the following:
- ServBay is installed and running: Download and install the latest ServBay from the official website.
- PHP is enabled in ServBay: In the ServBay control panel, make sure the PHP version you intend to use is enabled. Workerman requires PHP 5.4 or above; PHP 7.x or 8.x is recommended for best performance.
- Basic PHP and command-line knowledge: You should know basic PHP syntax and how to use command-line tools in the terminal.
Installing Workerman
1. Ensure Composer is Available
Composer is already built into ServBay, so no separate installation is needed. Just confirm that ServBay is running and the desired PHP version is enabled. ServBay will automatically configure Composer for the corresponding PHP version. You can access Composer via ServBay’s terminal or an external terminal (if ServBay has added PHP and Composer to your system PATH).
To check if Composer is available, open a terminal and run:
bash
composer -v
1
If Composer is correctly installed and configured within ServBay's PHP environment, you should see the Composer version info. If the command isn't found, check that ServBay is running and the PHP version is enabled.
2. Create the Project Directory
Navigate to the recommended ServBay website root, create, and enter a new project folder:
macOS:
bash
cd /Applications/ServBay/www
mkdir servbay-workerman-demo
cd servbay-workerman-demo
1
2
3
2
3
Windows:
cmd
cd C:\ServBay\www
mkdir servbay-workerman-demo
cd servbay-workerman-demo
1
2
3
2
3
Here we create a folder named servbay-workerman-demo
to hold Workerman project files.
3. Install Workerman via Composer
Within the project directory, use Composer to install Workerman. This is the recommended approach, as Composer will handle dependencies automatically.
Project directory paths:
- macOS:
/Applications/ServBay/www/servbay-workerman-demo
- Windows:
C:\ServBay\www\servbay-workerman-demo
bash
composer require workerman/workerman
1
Composer will download Workerman and its dependencies into the vendor
folder in your project.
Writing Workerman HTTP Server Code
The HTTP server is one of Workerman's most common use cases for building high-performance web apps or API services.
Inside your project directory, create a file named http_server.php
(or any name you prefer, like server.php
) and add the following PHP code:
php
<?php
// Include Composer autoload to use Workerman classes
require __DIR__ . '/vendor/autoload.php';
// Import Workerman's Worker class
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Response;
// Create a Worker instance, specify protocol and address
// 'http://0.0.0.0:8080' creates an HTTP server listening on all interfaces on port 8080
// 0.0.0.0 allows access from localhost or LAN devices; 8080 is the port to listen on.
$http_worker = new Worker('http://0.0.0.0:8080');
// Set number of Worker processes
// Here it's set to 4, meaning 4 PHP processes will handle requests; adjust as needed for your CPU cores
$http_worker->count = 4;
// Define logic for handling client messages (HTTP requests)
// $connection is the active connection object to send responses
// $request is the current request object with details (URL, Headers, Body, etc.)
$http_worker->onMessage = function(TcpConnection $connection, Request $request) {
// Send a simple string as HTTP response to the client
// Workerman's HTTP protocol automatically handles headers and details
$connection->send(new Response(200, [], 'Hello ServBay Workerman HTTP Server!'));
};
// Run all Worker instances
// This is the Workerman event loop; once started, Worker processes listen to the port and handle events
Worker::runAll();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Code Explanation:
require __DIR__ . '/vendor/autoload.php';
- Loads Composer's autoloader so you can use Workerman classes (Worker
,Request
,Response
etc).use Workerman\...;
- Imports the necessary classes.new Worker('http://0.0.0.0:8080')
- Creates a Workerman instance specifying the protocol (http
) and address (0.0.0.0:8080
).$http_worker->count = 4;
- Sets the number of Workerman worker processes. Increasing this can utilize multi-core CPUs for higher concurrency.$http_worker->onMessage = function(TcpConnection $connection, Request $request) { ... };
- Defines the callback executed when Workerman receives a full HTTP request.$connection
sends data to the client,$request
contains request info. UseResponse
to create standard HTTP responses.Worker::runAll();
- Starts Workerman’s event loop, making all defined Worker instances begin listening and handling connections.
Running the Workerman HTTP Server
In your project directory, start the HTTP server by running:
Project directory paths:
- macOS:
/Applications/ServBay/www/servbay-workerman-demo
- Windows:
C:\ServBay\www\servbay-workerman-demo
bash
php http_server.php start
1
Run mode explanations:
- Foreground mode: Running
php http_server.php start
will launch Workerman in the foreground, with logs output to the terminal. UseCtrl+C
to stop. Best for development and debugging. - Daemon mode: For production, run Workerman as a background daemon using the
-d
option:bashWorkerman will run in the background, outputting logs to a log file (by default within the Workerman directory or a specified path).php http_server.php start -d
1
Process Management:
Workerman offers convenient process management commands:
- Start:
php http_server.php start
(foreground) orphp http_server.php start -d
(background) - Stop:
php http_server.php stop
(gracefully exits after finishing current requests) - Restart:
php http_server.php restart
(stops then starts) - Smooth Reload:
php http_server.php reload
(used for code updates, gracefully restarts child processes without interrupting the service; watch out for lifecycle hooks likeonWorkerStart
) - Status:
php http_server.php status
(shows Workerman process status, memory usage, connection count, etc.)
Once the server is running, open your browser and visit http://localhost:8080
or http://127.0.0.1:8080
. You should see the page display Hello ServBay Workerman HTTP Server!
.
Creating a WebSocket Server with Workerman
The WebSocket protocol lets clients and servers establish persistent, bidirectional connections—perfect for building real-time apps like chat rooms, stock tickers, games, and more. Workerman has strong WebSocket support.
Write the WebSocket Server Code
Create a file called
websocket_server.php
in your project directory and insert the code below:php<?php require __DIR__ . '/vendor/autoload.php'; use Workerman\Worker; use Workerman\Connection\TcpConnection; // Create a WebSocket server listening on port 8081 // 'websocket://0.0.0.0:8081' sets up a WebSocket service // Workerman automatically handles the WebSocket handshake $ws_worker = new Worker('websocket://0.0.0.0:8081'); // Start 4 processes to handle connections $ws_worker->count = 4; // Logic for when a new connection is established // Triggered when a new client connects to the server $ws_worker->onConnect = function(TcpConnection $connection) { echo "New WebSocket connection from " . $connection->getRemoteIp() . "\n"; }; // Logic for receiving messages // Triggered when the server receives a WebSocket message from the client // $data is the message content received from the client (decoded) $ws_worker->onMessage = function(TcpConnection $connection, $data) { echo "Received message: " . $data . "\n"; // Echo received message back to the client // $connection->send() automatically encodes data into a WebSocket frame $connection->send('ServBay Workerman received: ' . $data); }; // Logic for when connection is closed // Triggered when the client disconnects $ws_worker->onClose = function(TcpConnection $connection) { echo "WebSocket Connection closed\n"; }; // Optional: error handling logic $ws_worker->onError = function(TcpConnection $connection, $code, $msg) { echo "Error: $code - $msg\n"; }; // Run all Worker instances Worker::runAll();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44Run the WebSocket Server
In your project directory, start the WebSocket server:
bashphp websocket_server.php start
1You can also use
-d
for background mode. Once running, use any WebSocket client to connect tows://localhost:8081
.For example, in your browser’s developer Console, use JavaScript to test:
javascriptvar ws = new WebSocket("ws://localhost:8081"); ws.onopen = function(event) { console.log("WebSocket connection opened"); ws.send("Hello from Browser!"); // send message }; ws.onmessage = function(event) { console.log("Message from server:", event.data); // receive messages }; ws.onclose = function(event) { if (event.wasClean) { console.log("WebSocket connection closed cleanly, code=" + event.code + " reason=" + event.reason); } else { console.error("WebSocket connection died"); } }; ws.onerror = function(error) { console.error("WebSocket error:", error); }; // Close connection (optional) // ws.close();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25On successful connection, you'll see the terminal output connection info; after sending a message, the terminal logs the message, and the browser receives the echo from the server.
Creating a TCP Server with Workerman
Workerman can also be used to build general TCP servers to support applications based on the TCP protocol—useful for gaming backends, IoT platforms, custom communication services, etc.
Write the TCP Server Code
Create
tcp_server.php
in your project directory and add:php<?php require __DIR__ . '/vendor/autoload.php'; use Workerman\Worker; use Workerman\Connection\TcpConnection; // Create a TCP server listening on port 8082 // 'tcp://0.0.0.0:8082' sets up a TCP server // By default, Workerman uses the Text protocol (line ending '\n'); you can specify or customize protocols as needed $tcp_worker = new Worker('tcp://0.0.0.0:8082'); // Start 4 processes to handle connections $tcp_worker->count = 4; // Logic for new connections $tcp_worker->onConnect = function(TcpConnection $connection) { echo "New TCP connection from " . $connection->getRemoteIp() . "\n"; // Send welcome message upon connection $connection->send("Welcome to ServBay Workerman TCP Server!\n"); }; // Logic for message reception // $data is the raw TCP data received from the client (parsed per protocol) $tcp_worker->onMessage = function(TcpConnection $connection, $data) { echo "Received data: " . $data; // Echo received data back to the client $connection->send('ServBay Workerman received: ' . $data); }; // Logic when connection closes $tcp_worker->onClose = function(TcpConnection $connection) { echo "TCP Connection closed\n"; }; // Run all Worker instances Worker::runAll();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36Run the TCP Server
In your project directory, start the TCP server:
bashphp tcp_server.php start
1You can also use the
-d
option for background mode. After starting, use a TCP client tool to connect tolocalhost:8082
.For example, launch another terminal and use
telnet
ornc
:bash# Using telnet telnet localhost 8082 # Or with nc (netcat) nc localhost 8082
1
2
3
4
5On connection, you'll see a welcome message from the server. Enter any text (end with Enter; Workerman uses the Text protocol by default), and the server will echo your message.
Important Notes
- Port Usage: Make sure the ports that Workerman listens on (8080, 8081, 8082 in these examples) aren’t already in use by your macOS system or other ServBay services. If there's a conflict, Workerman will fail to start and report an error. Use
lsof -i :port
to check port usage. - Firewall: Your OS firewall may block external devices from accessing these ports. This isn't usually a problem for local development, but if you need LAN devices to reach Workerman services, check and configure firewall settings.
- Relationship with ServBay’s Web Servers: Workerman runs on its own ports and is an independent process/service from ServBay's Caddy or Nginx. Workerman apps typically handle connections directly and aren’t proxied via Caddy/Nginx (unless you set up reverse proxying manually). Workerman excels at long connections and async high-concurrency workloads (WebSocket), while ServBay's Caddy/Nginx is best for classic, short-lived HTTP requests.
- PHP Version: Ensure your ServBay PHP version meets Workerman's minimum requirements. ServBay ships with multiple PHP versions; select and enable the one that best fits your project via the ServBay control panel.
- Extension Dependencies: Workerman relies on certain PHP extensions for best performance (e.g.,
event
—if installed/enabled, Workerman uses it for maximum efficiency; alsoposix
,pcntl
for multi-process support). ServBay enables most common extensions by default, but if you encounter issues, check your PHP extension settings in the ServBay control panel. - Logs: In daemon mode, Workerman's output is redirected to log files. Regularly check logs to monitor application status and troubleshoot potential errors.
FAQ (Frequently Asked Questions)
- Q: How do I stop the Workerman server?
- A: If the server runs in the foreground (
start
command), pressCtrl+C
in the terminal. If in the background as a daemon (start -d
), usephp your_server_file.php stop
in the project directory to stop.
- A: If the server runs in the foreground (
- Q: Why won't the Workerman server start?
- A: The most common reason is the server port is already in use. Check the error message in the terminal; usually, it will mention port usage. Try changing to a free port or stop other processes using it. Run
lsof -i :port
to see which process is occupying a port.
- A: The most common reason is the server port is already in use. Check the error message in the terminal; usually, it will mention port usage. Try changing to a free port or stop other processes using it. Run
- Q: What's the difference between ServBay's Caddy/Nginx and Workerman? Which should I use?
- A: ServBay’s Caddy/Nginx are traditional web servers meant for standard HTTP/HTTPS requests, usually working with PHP-FPM, where PHP processes terminate after handling a request. Workerman is a PHP asynchronous network framework, running as a memory-resident process—it can act as its own HTTP server and handle WebSocket, TCP, and other protocols, making it ideal for high-concurrency, long-connection, and real-time apps. Use Caddy/Nginx for classic websites or REST APIs. For chat rooms, game backends, IoT services, etc., choose Workerman. You may also combine them, e.g., use Caddy/Nginx as a reverse proxy forwarding specific requests to Workerman.
- Q: Can I run multiple Workerman apps simultaneously in ServBay?
- A: Yes. Each Workerman app runs in its own PHP process and should listen on a unique port. Just create separate server scripts for each app and start them in different terminal windows (or as background processes). Make sure their ports don’t clash.
Summary
By following this guide, you've learned how to quickly set up and run Workerman projects in the efficient ServBay local development environment. Workerman's performance and asynchronous capabilities give PHP developers incredible power to build next-generation network applications. With ServBay’s built-in Composer and PHP, you can boost development speed and focus on your business logic, not the setup process. Whether you're building high-performance web services or real-time interactive WebSocket apps, ServBay is the ideal local development partner for Workerman. We hope this guide helps you start your Workerman journey smoothly!