DownloadWebSocket Server with Logging & Event Triggering
This case study demonstrates how Ascoos OS can implement a WebSocket server that logs incoming messages and triggers semantic events using the built-in event system.
Purpose
-
Accept multiple WebSocket client connections
-
Decode incoming messages
-
Trigger semantic events (e.g., message received, client connected/disconnected)
-
Log all activity to a file
-
Echo messages back to clients
Main Classes from Ascoos OS
-
TWebSocketHandler
WebSocket server creation, socket binding, frame handling, client management
-
TEventHandler
Event registration, triggering, and logging
File Structure
The logic is implemented in a single PHP file:
- websocket_logger.php
It includes all steps: socket setup, event registration, message handling, and logging.
Requirements
-
PHP ? 8.2
-
Installed Ascoos OS or
AWES 26
Execution Flow
-
Define logging configuration.
-
Initialize `TWebSocketHandler` and `TEventHandler`.
-
Register events for message and connection handling.
-
Enable WebSocket mode and bind to port.
-
Listen for incoming connections.
-
Handle multiple clients and decode messages.
-
Trigger events and log activity.
-
Echo messages back to clients.
Example Code
$ws = new TWebSocketHandler($properties);
$events = new TEventHandler([], $properties);
$events->register('ws', 'message.received', fn($msg) => $events->logger->log("Message received: $msg"));
$events->register('ws', 'client.connected', fn($client) => $events->logger->log("Client connected: $client"));
$events->register('ws', 'client.disconnected', fn($client) => $events->logger->log("Client disconnected: $client"));
$ws->enableWebSocket();
$ws->createSocket();
$ws->bindSocket('0.0.0.0', 8080);
$ws->listenSocket(5);
$ws->handleMultipleClients(function ($client, $data) use ($ws, $events) {
$message = $ws->receiveWebSocketFrame();
$events->trigger('ws', 'message.received', $message);
$ws->sendWebSocketFrame("Echo: $message");
}, timeout: 30);
Expected Output
Log file: websocket_activity.log
Client connected: 192.168.255.255
Message received: Hello Server
Client disconnected: 192.168.255.255
Resources
Contribution
You can extend the logic to support authentication, message routing, or persistent sessions. See CONTRIBUTING.md for guidelines.
License
This case study is covered under the Ascoos General License (AGL). See LICENSE.md.
|