Setting Up and Running Workerman Applications in ServBay
Overview
This documentation 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 development environment using ServBay’s integrated PHP and Composer. Workerman is a powerful PHP library ideal for building network services requiring high concurrency, such as web servers, real-time communication servers, game servers, and more. ServBay offers a ready-to-use development platform that greatly simplifies the Workerman environment setup process.
What is Workerman?
Workerman is an open-source, high-performance asynchronous network communication framework written entirely in PHP. It utilizes an EventLoop mechanism to achieve asynchronous, non-blocking I/O, efficiently handling large numbers of concurrent connections. Unlike the traditional PHP web development model (such as Apache/Nginx + PHP-FPM), Workerman applications typically run as resident processes in memory, listening on specific ports and directly handling network connections and data. This avoids the overhead of process destruction after each request, greatly enhancing performance and throughput.
Using Workerman, developers can easily build:
- High-performance HTTP servers that can even replace Apache/Nginx for handling simple static or dynamic requests.
- Real-time WebSocket servers for building chatrooms, real-time data push services, etc.
- Custom protocol TCP/UDP servers.
- Command-line tools, scheduled tasks, microservices, and more.
Workerman’s Core Features and Advantages
- High Performance: Event-driven and asynchronous non-blocking I/O core, handling massive concurrent connections and delivering outstanding performance.
- Multi-Protocol Support: Native support for HTTP, WebSocket, TCP, UDP, and more, plus flexible interfaces for custom protocols.
- Easy to Use: Provides a concise and intuitive API, lowering the complexity of asynchronous network programming so PHP developers can get started quickly.
- Flexible Scalability: Supports a multi-process model, making it easy to leverage multi-core CPUs for horizontal scaling and load balancing. Easily integrates Composer packages and existing PHP libraries.
- PHP Ecosystem Integration: As a PHP library, it integrates tightly with the PHP ecosystem and can seamlessly use Composer for dependency management.
- Daemon Mode: Supports running as a stable background daemon process, making it suitable for production deployments and ensuring service continuity.
Workerman opens the door 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 tailor-made for web developers. It integrates runtimes for PHP, Node.js, Python, Go, Java, and more, as well as popular databases and server software like Caddy, Nginx, Apache, MySQL, PostgreSQL, MongoDB, Redis, and Memcached. ServBay’s main advantage is its out-of-the-box experience, especially its pre-configured Composer environment, which greatly facilitates building and running Workerman projects in ServBay.
This guide will walk you through creating several basic examples to demonstrate how to quickly set up and run Workerman applications in ServBay, including a simple HTTP server, a WebSocket server, and a TCP server.
TIP
For better management and standards, ServBay recommends storing all local website project files in the /Applications/ServBay/www
directory. All project path examples in this document are based on this directory.
Prerequisites
Before getting started, make sure you meet the following requirements:
- ServBay is installed and running properly: Download and install the latest ServBay from the official website.
- PHP is enabled in ServBay: In the ServBay control panel, ensure your desired PHP version is enabled. Workerman requires PHP 5.4 or above, with PHP 7.x or 8.x recommended for best performance.
- Basic knowledge of PHP and command-line operations: You should be familiar with basic PHP syntax and using command-line tools in the terminal.
Installing Workerman
1. Ensure Composer is Available
ServBay comes with Composer pre-installed. You don’t need to install it separately. Just ensure ServBay is started and that your chosen PHP version is enabled. ServBay will automatically configure the corresponding Composer environment for each PHP version. You can use Composer from ServBay’s terminal or an external terminal (if ServBay has added PHP and Composer to your system PATH).
Open a terminal and verify Composer availability with:
composer -v
If Composer is installed and configured correctly in ServBay’s PHP environment, you'll see the Composer version information. If the command is not found, check whether ServBay is running and that your PHP version is enabled.
2. Create Your Project Directory
Navigate to ServBay’s recommended web root directory, create a new project directory, and enter it:
cd /Applications/ServBay/www
mkdir servbay-workerman-demo
cd servbay-workerman-demo
2
3
Here, we created a directory named servbay-workerman-demo
to store the Workerman project files.
3. Install Workerman Using Composer
Inside your project directory (/Applications/ServBay/www/servbay-workerman-demo
), install the Workerman library with Composer (recommended, handles dependencies automatically):
composer require workerman/workerman
Composer will automatically download Workerman and its dependencies into the vendor
directory in your project.
Writing Workerman HTTP Server Code
The HTTP server is one of Workerman’s most common use cases, suitable for building high-performance web apps or API services.
In your project directory, create a file named http_server.php
(or your preferred name, e.g., server.php
) and add the following PHP code:
<?php
// Include Composer’s autoloader file 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 and specify the protocol and address to listen on
// 'http://0.0.0.0:8080' means creating an HTTP server listening on all network interfaces (0.0.0.0) at port 8080
// 0.0.0.0 allows access from the local machine or other devices on the LAN; 8080 is the port number
$http_worker = new Worker('http://0.0.0.0:8080');
// Set the number of Worker processes
// Here set to 4, meaning 4 independent PHP processes will handle requests (adjust based on CPU cores)
$http_worker->count = 4;
// Define logic to handle client messages (HTTP requests)
// $connection is the current connection object for sending responses to the client
// $request is the current request object containing detailed request info (URL, headers, body, etc.)
$http_worker->onMessage = function(TcpConnection $connection, Request $request) {
// Send a simple string as the HTTP response to the client
// Workerman’s HTTP protocol will automatically handle HTTP response headers, etc.
$connection->send(new Response(200, [], 'Hello ServBay Workerman HTTP Server!'));
};
// Run all Worker instances
// This is Workerman’s main loop; after starting, Worker processes listen on ports and process events
Worker::runAll();
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, making Workerman’s classes (Worker
,Request
,Response
, etc.) available.use Workerman\...;
: Imports the required 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 processes to start. Increasing the process count leverages 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. The$connection
object sends data back to the client; the$request
object contains request details. TheResponse
class builds a standard HTTP response.Worker::runAll();
: Starts Workerman’s event loop, running all defined Worker instances to listen for and process connections.
Running the Workerman HTTP Server
In your project directory (/Applications/ServBay/www/servbay-workerman-demo
), open the terminal and start the HTTP server with:
php http_server.php start
Running Modes:
- Foreground Mode: Running
php http_server.php start
keeps Workerman in the foreground, outputting logs and info to the terminal. Stop the server withCtrl+C
. Useful for development and debugging. - Daemon Mode: For production, run Workerman as a background daemon using the
-d
option:bashWorkerman will run in the background, redirecting output to log files (by default in the Workerman directory or a specified path).php http_server.php start -d
1
Process Management Commands:
Workerman offers several handy process control commands:
- Start:
php http_server.php start
(foreground) orphp http_server.php start -d
(background) - Stop:
php http_server.php stop
(waits for requests to finish and exits gracefully) - Restart:
php http_server.php restart
(stops then starts) - Reload:
php http_server.php reload
(for smooth code updates; restarts child processes one by one without interrupting service. Note use of lifecycle hooks likeonWorkerStart
.) - Status:
php http_server.php status
(shows Workerman process status, memory usage, connections, etc.)
After starting the server, open your browser and visit http://localhost:8080
or http://127.0.0.1:8080
. You should see the output Hello ServBay Workerman HTTP Server!
.
Creating a WebSocket Server with Workerman
The WebSocket protocol allows for persistent two-way communication between client and server, perfect for real-time applications like chatrooms, stock tickers, games, etc. Workerman has excellent WebSocket support.
Create WebSocket Server Code
In your project directory, create
websocket_server.php
and add:php<?php require __DIR__ . '/vendor/autoload.php'; use Workerman\Worker; use Workerman\Connection\TcpConnection; // Create a WebSocket server instance, listening on port 8081 // 'websocket://0.0.0.0:8081' means create a WebSocket server // 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 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 when a message is received // Triggered when the server receives a WebSocket message from a client // $data is the decoded message from the client $ws_worker->onMessage = function(TcpConnection $connection, $data) { echo "Received message: " . $data . "\n"; // Echo the received message back to the client // $connection->send() automatically encodes it as a WebSocket frame $connection->send('ServBay Workerman received: ' . $data); }; // Logic for when the connection is closed // Triggered when a client disconnects $ws_worker->onClose = function(TcpConnection $connection) { echo "WebSocket Connection closed\n"; }; // Error handling logic (optional) $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
Start the WebSocket server in your project directory:
bashphp websocket_server.php start
1You can also use the
-d
option to run as a background daemon. Connect to the server atws://localhost:8081
using any WebSocket client.For example, you can test directly using JavaScript in your browser console:
javascriptvar ws = new WebSocket("ws://localhost:8081"); ws.onopen = function(event) { console.log("WebSocket connection opened"); ws.send("Hello from Browser!"); // Send a message }; ws.onmessage = function(event) { console.log("Message from server:", event.data); // Receive a message }; 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 the 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
25Once connected, you’ll see connection info printed in your terminal. Sending a message will display the message in the terminal, and the browser will receive the echoed response from the server.
Creating a TCP Server with Workerman
Workerman can also be used to create generic TCP servers for any kind of application-layer TCP data. This is highly useful for game backends, IoT platforms, custom communication services, and more.
Create TCP Server Code
In your project directory, create
tcp_server.php
and add:php<?php require __DIR__ . '/vendor/autoload.php'; use Workerman\Worker; use Workerman\Connection\TcpConnection; // Create a TCP server instance listening on port 8082 // 'tcp://0.0.0.0:8082' means creating a TCP server // By default, Workerman uses the Text protocol (newline '\n'), but you can specify or implement custom protocols $tcp_worker = new Worker('tcp://0.0.0.0:8082'); // Start 4 processes to handle connections $tcp_worker->count = 4; // Logic for when a connection is established $tcp_worker->onConnect = function(TcpConnection $connection) { echo "New TCP connection from " . $connection->getRemoteIp() . "\n"; // Send welcome message on connection $connection->send("Welcome to ServBay Workerman TCP Server!\n"); }; // Logic for when a message is received // $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 the received data back to the client $connection->send('ServBay Workerman received: ' . $data); }; // Logic for when the connection is closed $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
Start the TCP server in your project directory:
bashphp tcp_server.php start
1You can also use the
-d
option to run in the background. After launching, connect using any TCP client tolocalhost:8082
.For example, on macOS/Linux, open another terminal window and use
telnet
ornc
(netcat):bash# Using telnet telnet localhost 8082 # Or using nc (netcat) nc localhost 8082
1
2
3
4
5After connecting, you'll see the server’s welcome message. Type any text (followed by Enter, since the default is the Text protocol), and the server will echo back what you sent.
Notes and Best Practices
- Port Usage: Make sure the ports Workerman listens on (8080, 8081, 8082 in these examples) are not already used by other services on your macOS system or ServBay. If there’s a conflict, Workerman will fail to start and show an error. Use
lsof -i :PORTNUMBER
to check which process is using a port. - Firewall: macOS’s built-in firewall may block external devices from accessing these ports. This is usually not an issue for local development, but if you want other LAN devices to access your Workerman service, check and adjust your macOS firewall settings as needed.
- Relation to ServBay Web Servers: Workerman listens on its own ports and runs as an independent process, separate from Caddy or Nginx running in ServBay. Workerman usually handles connections directly (unless you specifically configure reverse proxying). Workerman is best for use cases needing persistent connections or high-concurrency asynchronous handling (e.g. WebSocket), while Caddy/Nginx in ServBay is for traditional, short-lived HTTP requests.
- PHP Version: Ensure the PHP version in ServBay running Workerman meets the minimum requirement. ServBay supports and pre-installs multiple PHP versions; select and enable the appropriate one for your project in the ServBay panel.
- Extension Dependencies: Workerman depends on certain PHP extensions for best performance and features, such as the
event
extension (used by default if enabled, for better performance), as well asposix
andpcntl
(for multi-process mode). ServBay enables most common extensions by default, but check the panel if you encounter issues to ensure required extensions are enabled. - Logs: In daemon mode, Workerman’s output is redirected to log files. Check log files periodically to monitor application status or catch potential errors.
Frequently Asked Questions (FAQ)
- Q: How do I stop the Workerman server?
- A: If running in the foreground (
start
command), simply pressCtrl+C
in the terminal. If running in the background as a daemon (start -d
), in your project directory usephp your_server_file.php stop
to stop the server.
- A: If running in the foreground (
- Q: Why won’t my Workerman server start?
- A: The most common reason is the listening port is already in use. Check the error message in the terminal; it usually indicates a port conflict. Try a different port, or stop the process using that port. Run
lsof -i :PORTNUMBER
to see which process is occupying the port.
- A: The most common reason is the listening port is already in use. Check the error message in the terminal; it usually indicates a port conflict. Try a different port, or stop the process using that port. Run
- Q: What’s the difference between ServBay’s Caddy/Nginx and Workerman? Which should I use?
- A: Caddy/Nginx in ServBay are traditional web servers, mainly for handling standard HTTP/HTTPS requests (usually in tandem with PHP-FPM). Each request typically ends the PHP process. Workerman is an asynchronous PHP network framework that can act as an HTTP server or handle WebSocket/TCP and more. It runs as a persistent process and is better for high-concurrency, long-lived, or real-time communications. For traditional websites or RESTful APIs, use Caddy/Nginx. For real-time chat, game backends, IoT, or similar, use Workerman. You can also combine them: for example, use Caddy/Nginx as a reverse proxy forwarding certain requests to Workerman.
- Q: Can I run multiple Workerman applications in ServBay at the same time?
- A: Yes. Each Workerman app needs to run in its own PHP process, each listening on a different port. Just write separate startup scripts for each and run
php your_app_server.php start
(or in the background) in separate terminals. Make sure their ports do not conflict.
- A: Yes. Each Workerman app needs to run in its own PHP process, each listening on a different port. Just write separate startup scripts for each and run
Conclusion
With this guide, you’ve learned how to quickly set up and run Workerman projects in ServBay, an efficient local development environment. Thanks to its high performance and asynchronous architecture, Workerman empowers PHP developers to build the next generation of network applications. Combining this with ServBay’s out-of-the-box Composer and PHP environment, you can greatly boost your development efficiency and focus on implementing business logic for your Workerman apps, instead of spending time on environment setup. Whether you’re building high-performance web services or developing interactive, real-time WebSocket apps, ServBay is your ideal local development partner for Workerman. We hope this guide helps you launch your Workerman journey with ease!