Building High-Performance PHP Applications with Swoole in ServBay
ServBay is a local web development environment specifically designed for developers, pre-integrated with various languages, databases, and tools to simplify local workflows. This guide focuses on empowering your PHP projects with the Swoole extension within ServBay, enabling you to build efficient and scalable network services.
What is Swoole?
Swoole is a coroutine-based, parallel, and high-performance networking engine for PHP. Developed in pure C, it equips PHP with asynchronous, parallel, and coroutine networking capabilities. With Swoole, PHP developers can go beyond the limitations of the traditional request-response model (like Apache/Nginx + PHP-FPM) and handle high-concurrency tasks more efficiently, such as building long-running web servers, processing asynchronous tasks, or powering real-time services (e.g. WebSocket).
Key Features of Swoole:
- High Performance: Built with C language, offering asynchronous I/O and multi-process/multi-threading support.
- Coroutines: Lightweight coroutines bring asynchronous execution to synchronous code, simplifying asynchronous logic.
- Comprehensive Protocol Support: Native support for TCP/UDP/HTTP/WebSocket and more network protocols.
- Easy to Use: Clean APIs designed for PHP developers.
- Resident Memory: Apps run as persistent processes, avoiding the startup overhead of reinitializing PHP on every request.
Thanks to Swoole, PHP is no longer just a scripting language for web development—it can now power a broad range of high-performance networking applications.
Enabling Swoole in ServBay
ServBay is designed to make it easy for developers to manage and use PHP extensions. Swoole, a crucial extension for modern high-performance PHP projects, comes pre-installed in ServBay. Getting started takes just a few steps.
Requirements:
- ServBay is installed and running.
- At least one PHP version is installed in ServBay.
Steps to Enable:
- Open the ServBay application interface.
- Navigate to the “Packages” or PHP version management section. (Note: Name may vary depending on your ServBay version but it's easily found on the main screen or in Settings.)
- Choose the PHP version where you want to enable Swoole.
- Locate the Swoole extension option and check to enable it. ServBay displays compiled extensions as a list or toggle switches.
- Save your changes and follow prompts to restart ServBay or the relevant PHP service. ServBay will auto-configure PHP to load the Swoole extension.
After completing these steps, you’ll be able to use Swoole in your chosen PHP version. Confirm it by running php -m
in the terminal—swoole
should show up among the loaded extensions.
TIP
ServBay recommends placing your websites and project files in the following directories for seamless site management and configuration:
- macOS:
/Applications/ServBay/www
- Windows:
C:\ServBay\www
The examples in this guide will use these suggested directories.
Creating a Simple Swoole HTTP Server
Now, let’s build a basic Swoole HTTP server to demonstrate handling web requests.
Step 1: Create Your Project Directory
Open your terminal, create a new project folder, and navigate into it. Following ServBay's recommendation:
macOS:
bash
cd /Applications/ServBay/www
mkdir servbay-swoole-http
cd servbay-swoole-http
1
2
3
2
3
Windows:
cmd
cd C:\ServBay\www
mkdir servbay-swoole-http
cd servbay-swoole-http
1
2
3
2
3
Step 2: Write the Server Script
In the servbay-swoole-http
directory, create a file named server.php
and add the following code:
php
<?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 successfully starts
$server->on("start", function (Server $server) {
echo "Swoole HTTP server is started at http://0.0.0.0:9501\n";
// You can log master process ID, manager process ID, etc. here
});
// Register 'request' event callback
// Triggered on each new HTTP request
$server->on("request", function (Request $request, Response $response) {
// Set HTTP response header
$response->header("Content-Type", "text/plain");
// 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 details available via $request
}
// Send response and end request
$response->end($content);
});
// Start the server
$server->start();
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
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 spins up a Swoole HTTP server listening on port 9501. It responds with "Hello ServBay!" for most requests and reveals request info on /info
.
Step 3: Run Your Swoole Server
Make sure you’re in the servbay-swoole-http
directory. Run your script using the PHP version in ServBay with Swoole enabled:
bash
php server.php
1
If successful, you’ll see this in your terminal:
bash
Swoole HTTP server is started at http://0.0.0.0:9501
1
Your Swoole HTTP server is now running and 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 the pages output Hello ServBay!
and request details, respectively.
To stop the server, return to the terminal and press Ctrl + C
.
Using Swoole for WebSocket Connections
Swoole natively supports WebSocket, making it perfect for real-time communication apps like chatrooms, game servers, or live data feeds.
Step 1: Create Your WebSocket Server Script
In your project folder (either reuse servbay-swoole-http
or create servbay-swoole-websocket
), add a file named websocket_server.php
:
Project directory paths:
- macOS:
/Applications/ServBay/www/servbay-swoole-http
- Windows:
C:\ServBay\www\servbay-swoole-http
php
<?php
use Swoole\WebSocket\Server;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
// Create Swoole WebSocket server instance
// (WebSocket server inherits from HTTP server and can handle HTTP requests too)
$server = new Server("0.0.0.0", 9502); // Listen on port 9502
// Register 'start' event callback, triggered on server start
$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 carries client connection info, $request->fd is the client file descriptor
$server->on("open", function (Server $server, Request $request) {
echo "connection open: {$request->fd}\n";
// Send a welcome message to client
$server->push($request->fd, "Welcome to ServBay WebSocket Demo!");
});
// Register 'message' event
// Triggered when the server receives a WebSocket message from client
// $frame contains message info, $frame->data is the content, $frame->fd is client's file descriptor
$server->on("message", function (Server $server, Frame $frame) {
echo "received message from {$frame->fd}: {$frame->data}\n";
// Reply to sender, or broadcast to all clients
// For example, reply to sender:
$server->push($frame->fd, "Hello, you sent: {$frame->data}");
// Example for broadcasting (requires managing connections or looping)
// foreach ($server->connections as $fd) {
// if ($fd != $frame->fd) { // Don't send back to sender
// $server->push($fd, "User {$frame->fd} says: {$frame->data}");
// }
// }
});
// Register 'close' event
// Triggered when a client connection closes
$server->on("close", function ($ser, $fd) {
echo "connection close: {$fd}\n";
});
// Start the server
$server->start();
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
44
45
46
47
48
49
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 on port 9502, with event handlers for when the server starts, when new connections open, when messages are received, and when connections close. Messages received are echoed back to the sender.
Step 2: Run the WebSocket Server
Be sure you’re in the directory containing websocket_server.php
. Execute:
bash
php websocket_server.php
1
If all goes well, your terminal will display:
bash
Swoole WebSocket server is started at ws://0.0.0.0:9502
1
Your Swoole WebSocket server is now running and listening on port 9502.
Step 3: Connect to Your WebSocket Server
You have multiple options for testing WebSocket connections.
Option A: Using Browser Developer Tools
Most modern browsers include developer tools (typically F12). Use the “Network” or “Console” panel to try out WebSocket connections:
Open any webpage (e.g.
about:blank
).Open Developer Tools, go to "Console".
Enter the following JavaScript code to connect:
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 upon connection }; ws.onmessage = function(event) { console.log("Message from server:", event.data); // Receive message }; ws.onerror = function(event) { console.error("WebSocket error:", event); // Error occurred }; ws.onclose = function(event) { console.log("WebSocket connection closed:", event); // Connection closed }; // Send more messages 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
21Check the console output—your server will log connections and incoming messages.
Option B: Using the wscat
Command-Line Tool
wscat
is a convenient CLI WebSocket client (Node.js-based):
Install
wscat
: If you don't have Node.js and npm, install them first. Then install wscat globally:bashnpm install -g wscat
1Connect to your WebSocket server: In your terminal, run:
bashwscat -c ws://localhost:9502
1After connecting, you'll see the
>
prompt.Send messages: Type a message and hit Enter:
bash> Hello ServBay via wscat
1The server will reply, and you'll see responses prefixed with
<
:bash< Hello, you sent: Hello ServBay via wscat
1Your server terminal will also print corresponding logs.
To disconnect, press Ctrl + C
in the wscat
terminal.
Tips & Important Notes
- Port Conflicts: Ensure your Swoole server’s port (9501, 9502, etc.) isn’t used by other applications or you'll be unable to start the server.
- PHP Version: When running scripts in your terminal, use the ServBay PHP version with Swoole enabled. Check your version with
php -v
. ServBay typically provides easy command-line tools to switch PHP versions. - Extension Status: If the server won’t start, verify that Swoole is enabled for your chosen PHP version and that you’ve restarted ServBay or the PHP service.
- Managing Resident Processes: Swoole servers run as persistent, in-memory processes. In production, use a process manager (like Supervisor, Systemd, or pm2) to keep Swoole running and restart it if it crashes. For ServBay local development, running manually in your terminal is usually sufficient.
Conclusion
With ServBay, it’s easy to enable and use the Swoole extension, allowing you to build and test high-performance PHP applications locally—whether you need classic HTTP services or modern, real-time WebSocket apps. Swoole’s advanced capabilities, paired with ServBay’s streamlined environment, open new horizons for PHP developers to create more efficient and powerful applications. Start exploring the possibilities of Swoole in ServBay today!