Building High-Performance PHP Applications with Swoole in ServBay
ServBay is a local web development environment designed specifically for developers. It comes pre-integrated with multiple language environments, databases, and tools, aiming to simplify the local development workflow. This article focuses on how to empower your PHP applications with the Swoole extension within ServBay, enabling you to build high-performance network services.
What Is Swoole?
Swoole is a coroutine-based, parallel, high-performance network communication engine designed for PHP. Written in pure C, it brings asynchronous, parallel, and coroutine networking capabilities to the PHP language. With Swoole, PHP developers can break free from the limitations of the classic web server request-response model (like Apache/Nginx + PHP-FPM) and handle high-concurrency tasks more efficiently—such as building resident memory web servers, asynchronous task processing, real-time communication (like WebSocket services), and more.
Core Features of Swoole:
- High Performance: Implemented in low-level C, offering asynchronous I/O, multi-process/multi-threading support.
- Coroutines: Lightweight coroutine support; write asynchronous code as if it were synchronous, greatly simplifying complex programming models.
- Rich Protocol Support: Natively supports TCP/UDP/HTTP/WebSocket and more.
- Easy to Use: Offers a clean and PHP-idiomatic API.
- Resident Memory: Applications run as persistent processes, eliminating the overhead of PHP environment initialization on every request.
With Swoole, PHP is no longer just a scripting language for web development—it’s now suited for a much wider range of high-performance network applications.
Enabling Swoole in ServBay
One of ServBay’s key goals is to let developers easily manage and use various PHP extensions. As a critical tool for modern high-performance PHP development, Swoole comes pre-installed in ServBay. Enabling it is just a matter of a few clicks.
Prerequisites:
- ServBay is installed and running.
- At least one PHP version is installed within ServBay.
How to Enable:
- Open the ServBay application interface.
- Navigate to the "Packages" or PHP version management section. (Note: The entry name might differ slightly depending on your version of ServBay, but it's typically in the main interface or within settings.)
- Select the PHP version where you want to enable Swoole.
- Locate the Swoole extension option and tick to enable it. ServBay displays precompiled extensions as a list or switch toggles.
- Save changes and restart ServBay or the relevant PHP service as prompted. ServBay will automatically configure the PHP environment to load the Swoole extension.
Once completed, you can start using Swoole in your chosen PHP version. To double-check, run php -m
in your terminal to see if swoole
appears in the list of loaded extensions.
TIP
ServBay recommends storing your website and project files in the /Applications/ServBay/www
directory for easier site management and configuration. In this guide, we'll also follow that path.
Building a Simple Swoole HTTP Server
Let’s create a basic Swoole HTTP server to demonstrate how to handle web requests.
Step 1: Create a Project Directory
Open your terminal, create, and enter a new project directory. Following ServBay’s recommendation, we’ll put it under /Applications/ServBay/www
:
cd /Applications/ServBay/www
mkdir servbay-swoole-http
cd servbay-swoole-http
2
3
Step 2: Write the Server Script
Inside the servbay-swoole-http
directory, create a file named server.php
and add the following code:
<?php
use Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;
// Create Swoole HTTP server instance
// Listen on all interfaces (0.0.0.0) at port 9501
$server = new Server("0.0.0.0", 9501);
// Register 'start' event callback
// Triggered when the server starts successfully
$server->on("start", function (Server $server) {
echo "Swoole HTTP server is started at http://0.0.0.0:9501\n";
// Here you can log master process ID, manager process ID, etc.
});
// Register 'request' event callback
// Triggered when a new HTTP request is received
$server->on("request", function (Request $request, Response $response) {
// Set response headers
$response->header("Content-Type", "text/plain");
// Handle logic based on request path or parameters
$path = $request->server['request_uri'] ?? '/';
$content = "Hello ServBay!";
if ($path === '/info') {
$content = "Request path: " . $path . "\n";
$content .= "Method: " . $request->server['request_method'] . "\n";
$content .= "Client IP: " . $request->server['remote_addr'] . "\n";
// More request info can be accessed via the $request object
}
// Send response body and end request
$response->end($content);
});
// Start the server
$server->start();
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
This script sets up a Swoole HTTP server listening on port 9501. When it receives a request, it returns a simple text response "Hello ServBay!". If you access the /info
endpoint, it will return some request details.
Step 3: Run the Swoole Server
Make sure your terminal is currently in the servbay-swoole-http
directory. Run the script using the PHP version in ServBay with Swoole enabled:
php server.php
If everything is working, you’ll see output like this in the terminal:
Swoole HTTP server is started at http://0.0.0.0:9501
That means the Swoole HTTP server is now up and running in the background, listening on port 9501.
Step 4: Access the Swoole Server
Open your web browser and visit:
http://localhost:9501
http://localhost:9501/info
You’ll see pages displaying Hello ServBay!
and, for /info
, a text response with request details.
To stop the server, return to the terminal window running the script and press Ctrl + C
.
Handling WebSocket Connections with Swoole
Swoole offers native support for the WebSocket protocol, making it ideal for building real-time features such as chat rooms, game servers, or live data push services.
Step 1: Create a WebSocket Server Script
In the /Applications/ServBay/www/servbay-swoole-http
directory (or create a new directory like servbay-swoole-websocket
), create a file named websocket_server.php
and add the following code:
<?php
use Swoole\WebSocket\Server;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
// Create a Swoole WebSocket server instance
// The WebSocket server extends the HTTP server, so it can handle both
$server = new Server("0.0.0.0", 9502); // Listen on port 9502
// Register 'start' event, triggered when the server starts
$server->on("start", function (Server $server) {
echo "Swoole WebSocket server is started at ws://0.0.0.0:9502\n";
});
// Register 'open' event
// Triggered when a new WebSocket connection is established
// $request contains client connection info; $request->fd is the client file descriptor
$server->on("open", function (Server $server, Request $request) {
echo "connection open: {$request->fd}\n";
// Optionally, send a welcome message to the client
$server->push($request->fd, "Welcome to ServBay WebSocket Demo!");
});
// Register 'message' event
// Triggered when the server receives a WebSocket message from a client
// $frame contains message info; $frame->data is the message content, $frame->fd is the client file descriptor
$server->on("message", function (Server $server, Frame $frame) {
echo "received message from {$frame->fd}: {$frame->data}\n";
// Optionally, broadcast to all clients or reply to the sender
// Here, just reply to the sender
$server->push($frame->fd, "Hello, you sent: {$frame->data}");
// Broadcast example (needs a connection list or traversal)
// foreach ($server->connections as $fd) {
// if ($fd != $frame->fd) { // Don’t send to sender
// $server->push($fd, "User {$frame->fd} says: {$frame->data}");
// }
// }
});
// Register 'close' event
// Triggered when a client connection is closed
$server->on("close", function ($ser, $fd) {
echo "connection close: {$fd}\n";
});
// Start the server
$server->start();
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
44
45
46
47
48
49
This script sets up a Swoole WebSocket server listening on port 9502. It defines several key event callbacks: start
(server startup), open
(new connection), message
(receiving a message), and close
(connection closed). In the message
event, the server sends the received message back with a prefix.
Step 2: Run the WebSocket Server
Make sure your terminal is in the directory containing websocket_server.php
. Run the script with ServBay’s PHP (Swoole enabled):
php websocket_server.php
If all goes well, you’ll see output like:
Swoole WebSocket server is started at ws://0.0.0.0:9502
This means the Swoole WebSocket server is running and listening on port 9502.
Step 3: Connect to the WebSocket Server
There are several ways to test connecting to your WebSocket server.
Method A: Using Browser Developer Tools
Most modern browsers include Network or Console panels in their dev tools (usually opened with F12) that allow you to test WebSocket connections.
Open any web page (such as
about:blank
).Open the DevTools, switch to the Console tab.
Enter the following JavaScript to establish a connection:
javascriptvar ws = new WebSocket("ws://localhost:9502"); ws.onopen = function(event) { console.log("WebSocket connection opened:", event); ws.send("Hello from Browser!"); // Send a message once connected }; ws.onmessage = function(event) { console.log("Message from server:", event.data); // Receive messages }; ws.onerror = function(event) { console.error("WebSocket error:", event); // Handle errors }; ws.onclose = function(event) { console.log("WebSocket connection closed:", event); // Connection closed }; // You can send messages anytime with ws.send("your message") // Close the connection with ws.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21Run this code in the console and observe the output. You’ll also see corresponding logs in the terminal running your
websocket_server.php
.
Method B: Using the wscat
CLI Tool
wscat
is a handy command-line WebSocket client tool based on Node.js.
Install
wscat
: If you don’t have Node.js and npm, install them first. Then installwscat
globally:bashnpm install -g wscat
1Connect to the WebSocket Server: Run the following command in your terminal:
bashwscat -c ws://localhost:9502
1Once connected, you’ll see a prompt (
>
).Send Messages: Type your message after the prompt and press Enter:
bash> Hello ServBay via wscat
1The server will reply. You’ll see a response in your terminal (starting with
<
):bash< Hello, you sent: Hello ServBay via wscat
1Likewise, logs will appear in the terminal running your
websocket_server.php
.
To disconnect from wscat
, press Ctrl + C
.
Notes and Troubleshooting
- Port Conflicts: Make sure that the ports used by your Swoole servers (such as 9501, 9502) are not occupied by other applications on your system. Swoole will fail to start if the port is already in use.
- PHP Version: When running scripts from the terminal, ensure you are using the PHP version in ServBay with Swoole enabled. You can check your current PHP version with
php -v
. ServBay often provides an easy command-line tool to switch PHP versions. - Extension Status: If the server fails to start, double-check that the Swoole extension is correctly enabled for your current PHP version in ServBay, and that ServBay or the PHP service has been restarted so changes take effect.
- Persistent Process Management: Swoole servers are persistent, in-memory processes. In production, use a process manager (like Supervisor, Systemd, pm2, etc.) to keep your Swoole processes running and auto-restart them if they crash. For local development in ServBay, running them directly from the terminal is typically sufficient.
Conclusion
With ServBay, you can easily enable and use the Swoole extension to build and test high-performance PHP applications in your local development environment—whether traditional HTTP services or modern, real-time WebSocket apps. The power of Swoole combined with ServBay’s streamlined local setup opens new possibilities for PHP developers, helping you build more efficient and robust applications. Give Swoole a try in ServBay today!