PHP Luminova: Real-Time Communication using HTTP Socket Server
Run a CLI socket listener and register handlers for incoming HTTP requests.
The Http Client Server class is designed to provide a flexible and efficient HTTP server for handling incoming requests. The server binds a stream socket, matches incoming HTTP requests to route callbacks, and writes the resulting HTTP response to the client socket. Run it from a bootstrapped CLI script with PHP’s PCNTL extension.
Key Features
- Address and Port Binding: Initialize the server with a specific address and port.
- Automatic Startup: Optionally start the server automatically upon creation.
- Flexible Routing: Route HTTP requests dynamically with support for
GET,POST, and other HTTP methods. - Request Accounting and Timeouts: Configure the connection counter and the listening socket timeout.
- Debugging Support: Enable or disable debug mode to output detailed information for troubleshooting.
- Port Management: Check if a port is in use and free it if necessary to prevent server failures.
- Graceful Shutdown: Cleanly close all connections and free up resources when the server is stopped.
Connection Processing
The server uses pcntl_fork() in both modes. Request callbacks run in the parent process after it waits for the child. Use sequential mode with an integer sleep value. Each HTTP response closes its client socket after writing.
Usage Examples
Basic Server Setup
In a bootstrapped CLI script, construct the server to bind a socket. Register routes before calling run(). The constructor starts the socket by default.
use Luminova\Http\Client\Server;
$server = new Server('127.0.0.1', 8080);
$server->ping();
$server->run(timeout: 1, sleep: 0);Rate Limiting
The server counts accepted connections by client address and resets the counter when the configured window elapses. Configure the threshold and its window before running the listener.
Set a threshold of 100 connections per 60 seconds.
$server->setRateLimit(100, 60);Connection Timeouts
Set the timeout on the listening stream. This setting also applies when the server is started again.
$server->setTimeout(30);Graceful Shutdown
Call shutdown() to close the listener and clear tracked connections.
$server->shutdown();HTTP Request Handling
Register the route before calling run(). The callback receives the framework request object and returns an HTTP message response or a complete HTTP response string.
use Luminova\Http\Client\Server;
use Luminova\Http\Message\Response;
use Luminova\Interface\RequestInterface;
$server = new Server('127.0.0.1', 8080);
$server->get('/', static function (RequestInterface $request): Response {
return new Response(
body: '<h1>Hello, World!</h1>',
headers: ['Content-Type' => ['text/html'], 'Connection' => ['close']]
);
});
$server->run(timeout: 1, sleep: 0);To return a raw response, replace the route callback in the preceding example. Include the status line, headers, and the blank line before the body.
$server->get('/', static function (RequestInterface $request): string {
return "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n"
. "Content-Length: 12\r\nConnection: close\r\n\r\nHello World!";
});curl "http://127.0.0.1:8080/"Debugging and Logs
If you're encountering issues, enabling debug mode provides more insights into what's going on.
$server->debug();To see which process is using a port, for example port 8080, use this command:
lsof -i :8080Server Shutdown
Graceful Termination with Signals
You can also handle signals like SIGINT (Ctrl+C) or SIGTERM for more graceful termination in CLI environments:
declare(ticks = 1);
pcntl_signal(SIGINT, function () use ($server) {
$server->shutdown();
exit;
});
pcntl_signal(SIGTERM, function () use ($server) {
$server->shutdown();
exit;
});Register Shutdown Function
In some cases, your script may exit unexpectedly due to an error or signal. You can use register_shutdown_function to ensure the socket is closed whenever the script exits:
register_shutdown_function([$server, 'shutdown']);Class Definition
- Class namespace:
Luminova\Http\Client\Server
Properties
guid
The fixed WebSocket protocol GUID used to calculate the upgrade response’s accept key. Leave this value unchanged.
public string $guid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';Methods
__construct
Initializes the HTTP server by binding to the specified address and port.
This constructor sets up the necessary properties for the HTTP server and optionally startsthe server immediately if $autostart is set to true. The server can bind to an IP addressor hostname, with an optional port. You can also pass stream context options for advanced configurations.
public function __construct(
string $address,
?int $port = null,
bool $autostart = true,
mixed $options = null
)Parameters:
| Parameter | Type | Description |
|---|---|---|
$address | string | The connection IP address, hostname or a valid TCP connection string to bind to (e.g., 127.0.0.1, example.com, or tcp://127.0.0.1:8080). |
$port | int|null | Optional port. When the address includes a transport scheme, supply the port in the address. |
$autostart | bool | Whether to start the server automatically upon initialization (default: true). |
$options | resource\|array<string,array<string,mixed>>\|null | Optional resource for stream context or an array of options to create stream_context_create resource (default: null). |
Throws:
- Luminova\Exceptions\RuntimeException - if the server fails to create a valid socket.
debug
Enables or disables debug mode for the application.
When debug mode is enabled, detailed debug messages will be output.This can be useful for troubleshooting and understanding application behavior during development or testing.
public function debug(bool $debug = true): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$debug | bool | Indicates whether to enable (true) or disable (false) debug mode. |
Return:
self - Returns instance of Http Server.
connectionRequired
Specifies whether the client must connect to the server before sending and receiving HTTP requests.
When set to true, the server requires clients to connect before making requests. In this case,you must implement connect() and disconnect() routes to handle the connection lifecycle.
public function connectionRequired(bool $required = true): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$required | bool | Whether a connection is required before handling requests (default: true). |
Return:
self - Returns instance of Http server.
For example:
- Clients should send a GET request to connect:
curl -X GET http://127.0.0.1:8080/connect. - Similarly, to disconnect:
curl -X GET http://127.0.0.1:8080/disconnect.
If set to false, you can handle the connection and disconnection logic manually without the needfor these specific routes.
websocket
Configures whether the server should accept WebSocket connections.
public function websocket(bool $accept = true): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$accept | bool | Whether to allow the WebSocket upgrade handshake path. The server closes the socket after writing its response. |
Return:
self - Returns instance of Http server.
isPortFree
Checks if the configured port is currently in use.
This method attempts to establish a connection to the provided addressand port. If a connection is successful, the port is considered in use.
public function isPortFree(): boolReturn:
bool - Returns true when the probe cannot open a connection, or false when it connects.
freePortIfStuck
Check if the port is in use and free it if necessary
public function freePortIfStuck(?int $port = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$port | int\|null | Port to inspect. Null uses the configured port. |
Return:
bool - Returns true when a process was found and no longer holds the port after termination. Uses lsof and sends SIGKILL to the returned process IDs.
setTimeout
Automatically close connections that are idle for too long.This can prevent resource exhaustion if clients stay connected without sending requests.
public function setTimeout(int $timeout, int $microseconds = 0): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$timeout | int | Timeout in seconds applied to the server’s listening stream. |
$microseconds | int | The microseconds part of the timeout to be set (default: 0). |
Return:
self - Returns instance of Http server.
setRateLimit
Sets the rate limit for incoming client requests.
This method defines the maximum number of requests a client can makewithin a specified time window (in seconds). Helps prevent abuse oroveruse of the server's resources.
public function setRateLimit(int $maxRequests, int $timeWindow): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$maxRequests | int | Accepted connection threshold per client address. A value at or below zero disables the threshold check. |
$timeWindow | int | Time window in seconds for the request limit. |
Return:
self - Returns instance of Http server.
setMaxProcesses
Set the upper limit the listener uses when tracking child processes in the run(simultaneous: true) path.
public function setMaxProcesses(int $max): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$max | int | Positive upper bound used for tracked child processes in simultaneous mode. |
Return:
self - Returns instance of Http server.
Throws:
- Luminova\Exceptions\RuntimeException - Throw if
$maxis not a positive integer.
setHeader
Set one entry in the server header configuration. To control the headers written to the client socket, set them on the HTTP response returned by the route.
public function setHeader(string $key, mixed $value): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The header key/name to set. |
$value | mixed | The value of the header key. |
Return:
self - Returns instance of Http server.
setHeaders
Replace the server header configuration. Set headers on the returned HTTP response to send them over the client socket.
public function setHeaders(array $headers): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$headers | array<string, mixed> | Associative array of headers, where the key is the header name and the value is the header value. |
Return:
self - Returns instance of Http server.
getSocket
Get the server socket resource for registration in the event loop.
public function getSocket(): mixedReturn:
resource|null - Returns the listening stream resource, null before binding or after shutdown, or false after a failed bind.
getId
Get the ID of the server socket.
public function getId(): intReturn:
int - Returns the integer resource ID when the socket is open, or zero when the socket is absent.
getAddress
Extracts the address and port from the DNS connection string.
If no address or port is found in the DNS, defaults to localhost(127.0.0.1) and port 8080.
public function getAddress(): arrayReturn:
array{address:string,port:int} - Returns the configured address and port. If no port was given, these are derived from the endpoint with defaults of 127.0.0.1 and 8080.
start
Starts the server by creating a socket and binding to the specified address and port.
This method attempts to create and bind a socket to the server's address and port. If the portis already in use or any other error occurs, an exception is thrown. Additionally, it enablesnon-blocking mode on the server socket.
public function start(): selfReturn:
self - Returns the Http Server instance after the socket is successfully created.
Throws:
- Luminova\Exceptions\RuntimeException - If the server cannot bind to the address or port, or if the port is already in use.
run
Runs the server and begins listening for incoming connections.
This method initiates the server to handle incoming client connections and processesrequests based on routes. It can either handle connections sequentially or simultaneously based onthe $simultaneous flag. The server will run in a loop until it is stopped.
public function run(
?int $timeout = 100000,
float|int $sleep = 0.1,
bool $simultaneous = false
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$timeout | int|null | Socket readiness timeout in seconds. Null polls without waiting. |
$sleep | float\|int | Pause between loop iterations, in seconds. Pass an integer when using sequential mode. |
$simultaneous | bool | Select the per-connection fork path. Request callbacks still execute in the parent. |
shutdown
Gracefully shuts down the server and closes the socket connection.
Closes the listener and clears the tracked connections, routes, and process records. Call shutdown() with its default argument for ordinary cleanup.
public function shutdown(bool $kill = false): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$kill | bool | Whether to attempt forced port cleanup on the applicable shutdown path. Defaults to false. |
on
Marks a client as connected to the server and sets its connection status.
public function on(?string $address = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$address | string|null | The client's IP address or identifier. Null uses the most recently tracked connection address. |
off
Marks a client as disconnected and removes it from the active clients list.
public function off(?string $address = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$address | string|null | The client's IP address or identifier. Null uses the most recently tracked connection address. |
accept
Register a route for all HTTP methods. The callback runs when the request path matches.
public function accept(string $pattern, Closure $response): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string | URI path pattern, such as / or /foo/{segment}. |
$response | \Closure | Callback receiving the request and returning an HTTP message response or a raw HTTP response string. |
get
Define a route for GET requests.
public function get(string $pattern, Closure $response): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string | URI pattern (e.g, '/') to match. |
$response | \Closure | The response callback. |
post
Define a route for POST requests.
public function post(string $pattern, Closure $response): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string | URI pattern (e.g, '/') to match. |
$response | \Closure | The response callback. |
ping
Register a simple "ping" route for health checks.
This method registers a GET /ping route, responding with a "PONG" message.It can be used to verify that the server is responsive. The response includesappropriate HTTP headers and a 200 OK status.
public function ping(): voiderror
Register an error response callback.
public function error(Closure $response): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$response | \Closure | The response callback. |
connect
Define a route for connection responses.
Registers GET /connect and returns the built-in connection response. The optional callback receives the selected client record and the full client map, in that order.
public function connect(?Closure $response = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$response | Closure\|null | Optional callback receiving array<string,mixed> $client and array<string,array<string,mixed>> $clients. Its return value is ignored. |
disconnect
Define a route for disconnection responses.
Registers GET /disconnect. The optional callback receives the selected client record marked disconnected and the full client map.
public function disconnect(?Closure $response = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$response | Closure\|null | Optional callback receiving array<string,mixed> $client and array<string,array<string,mixed>> $clients. Its return value is ignored. |
route
Register a route for one or more HTTP methods. Undefined method calls such as $server->put($pattern, $callback) also register a route using the method name as the HTTP verb.
public function route(
string $methods,
string $pattern,
Closure $response,
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$methods | string | HTTP methods to accept (e.g, GET\|POST\|PUT). |
$pattern | string | Path pattern. The server matches against the path without the query string. |
$response | \Closure | The response callback. |
onResponse
Sets a callback to intercept and modify the server response before sending it.
For ordinary HTTP requests, the closure receives the complete serialized response and parsed request headers. It must return a serialized HTTP response string. If the callback changes the body, it must also keep any Content-Length header consistent.
public function onResponse(Closure $intercept): voidExamples:
$server->onResponse(function(string $response, array $headers): string {
return preg_replace('/\r\n\r\n/', "\r\nX-Server: Luminova\r\n\r\n", $response, 1) ?? $response;
});Parameters:
| Parameter | Type | Description |
|---|---|---|
$intercept | \Closure | Callback to modify the response content. |