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 such as a stock price monitor.
Real-time monitoring applications are increasingly important in modern web development. Traditional HTTP communication cannot meet real-time requirements, but the WebSocket protocol can establish a long-lived, bidirectional connection between browsers and servers. PHP can be combined with WebSocket to develop such applications.
1. Understanding the WebSocket Protocol
The WebSocket protocol is a full‑duplex communication protocol based on TCP. By using WebSocket , browsers and servers can maintain a persistent connection, enabling real‑time two‑way communication, which is more suitable for monitoring applications than traditional HTTP.
2. Implementing a WebSocket Server in PHP
In PHP, you can use libraries such as Ratchet or ReactPHP to simplify WebSocket server development. Below is an example using Ratchet.
composer require cboden/ratchetSimple WebSocket server example:
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}\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
echo "Received message from client: {$from->resourceId}\n";
$data = json_decode($msg, true);
// handle message ...
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Client disconnected: {$conn->resourceId}\n";
}
public function onError(ConnectionInterface $conn, Exception $e) {
echo "An error occurred: {$e->getMessage()}\n";
$conn->close();
}
}
$server = new RatchetApp('localhost', 8080);
$server->route('/monitor', new MyServer(), ['*']);
$server->run();The code defines a MyServer class that implements Ratchet's MessageComponentInterface , providing callbacks for connection events.
3. Creating a WebSocket Connection with JavaScript
On the client side, JavaScript can establish a WebSocket connection and handle events.
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);
// process message ...
});
socket.addEventListener('close', function(event) {
console.log('Disconnected from server');
});
function sendMessage(message) {
socket.send(message);
}This script creates a WebSocket object, logs connection status, receives messages, and provides a send method to transmit data to the server.
4. Example: Real-Time Stock Price Monitoring
Below is a simple implementation of a stock price monitor using the previously defined server.
use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
require 'vendor/autoload.php';
class StockMonitor extends MyServer {
protected $stocks = [
'AAPL' => 0,
'GOOGL' => 0,
'MSFT' => 0,
];
public function onOpen(ConnectionInterface $conn) {
parent::onOpen($conn);
$this->sendStockPrices($conn);
}
public function sendStockPrices(ConnectionInterface $conn) {
foreach ($this->stocks as $symbol => $price) {
$this->stocks[$symbol] = rand(100, 200);
}
$conn->send(json_encode($this->stocks));
}
}
$server = new RatchetApp('localhost', 8080);
$server->route('/monitor', new StockMonitor(), ['*']);
$server->run();Client‑side code to receive and display the prices:
var stockPrices = {};
function displayStockPrices(prices) {
// render prices ...
}
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); }These examples demonstrate how PHP and WebSocket can be used to create real‑time monitoring applications, such as a live stock price dashboard, by leveraging Ratchet on the server and JavaScript on the client.
Conclusion
Using PHP together with the WebSocket protocol enables real‑time, bidirectional communication suitable for monitoring scenarios. Developers can simplify development with libraries like Ratchet and connect from browsers using JavaScript, gaining a clear understanding of WebSocket technology through practical examples.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.