Developing Real-Time Monitoring Applications with PHP and WebSocket

This article explains how to build real-time monitoring applications using PHP and the WebSocket protocol, covering the fundamentals of WebSocket, setting up a Ratchet server, creating client-side JavaScript connections, and providing complete code examples for a stock price monitoring demo.

php Courses
php Courses
php Courses
Developing Real-Time Monitoring Applications with PHP and WebSocket

1. Understanding the WebSocket protocol

WebSocket is a full‑duplex TCP‑based protocol that enables long‑lived connections between browsers and servers, allowing real‑time bidirectional communication, which is more suitable for monitoring applications than traditional HTTP.

2. Implementing a WebSocket server in PHP

PHP can create a WebSocket server using libraries such as Ratchet or ReactPHP. The article shows how to install Ratchet via Composer and provides a basic server implementation that implements MessageComponentInterface.

composer require cboden/ratchet

use RatchetMessageComponentInterface;
use RatchetConnectionInterface;

require 'vendor/autoload.php';

class MyServer implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo "New client connected: {$conn->resourceId}
";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        echo "Received message from client: {$from->resourceId}
";
        $data = json_decode($msg, true);
        // handle received message
        // ...
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        echo "Client disconnected: {$conn->resourceId}
";
    }

    public function onError(ConnectionInterface $conn, Exception $e) {
        echo "An error occurred: {$e->getMessage()}
";
        $conn->close();
    }
}

$server = new RatchetApp('localhost', 8080);
$server->route('/monitor', new MyServer(), ['*']);
$server->run();

3. Establishing a WebSocket connection with JavaScript

On the client side, JavaScript creates a new WebSocket object, registers event listeners for open, message, and close events, and defines a function to send messages to the server.

var socket = new WebSocket('ws://localhost:8080/monitor');

socket.addEventListener('open', function(event) {
    console.log('Connected to server');
});

socket.addEventListener('message', function(event) {
    console.log('Received message from server: ', event.data);
    // handle received message
    // ...
});

socket.addEventListener('close', function(event) {
    console.log('Disconnected from server');
});

function sendMessage(message) {
    socket.send(message);
}

4. Real‑time monitoring application example

The article demonstrates a simple stock‑price monitoring scenario. The server periodically generates random prices and pushes them to all connected clients; the client receives the data, stores it in a global variable, and calls a display function.

use RatchetMessageComponentInterface;
use RatchetConnectionInterface;

require 'vendor/autoload.php';

class StockMonitor extends MyServer {
    protected $stocks = [
        'AAPL' => 0, // Apple
        'GOOGL' => 0, // Google
        'MSFT' => 0, // Microsoft
    ];

    public function onOpen(ConnectionInterface $conn) {
        parent::onOpen($conn);
        $this->sendStockPrices($conn); // send initial prices
    }

    public function sendStockPrices(ConnectionInterface $conn) {
        foreach ($this->stocks as $symbol => $price) {
            $this->stocks[$symbol] = rand(100, 200); // random price
        }
        $conn->send(json_encode($this->stocks));
    }
}

$server = new RatchetApp('localhost', 8080);
$server->route('/monitor', new StockMonitor(), ['*']);
$server->run();
var stockPrices = {};

function displayStockPrices(prices) {
    // render prices on the page
    // ...
}

var socket = new WebSocket('ws://localhost:8080/monitor');

socket.addEventListener('open', function(event) {
    console.log('Connected to server');
});

socket.addEventListener('message', function(event) {
    var prices = JSON.parse(event.data);
    stockPrices = prices;
    displayStockPrices(prices);
});

socket.addEventListener('close', function(event) {
    console.log('Disconnected from server');
});

function sendMessage(message) {
    socket.send(message);
}

Conclusion

Using PHP together with WebSocket (e.g., Ratchet) and JavaScript enables developers to build real‑time monitoring applications with bidirectional communication, simplifying development through existing libraries and providing a solid foundation for various monitoring use cases.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

real-time monitoringWebSocketPHPRatchet
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.