Build Real-Time WebSocket Apps with PHP Ratchet: A Step‑by‑Step Guide
This tutorial explains the Ratchet PHP library for asynchronous WebSocket services, describes the WebSocket protocol and handshake process, and provides complete server‑side and client‑side code examples with installation steps to create a functional real‑time communication demo.
Ratchet Overview
Ratchet is a PHP library for building asynchronous WebSocket servers. It provides a simple API and allows composition of components without modifying existing code.
WebSocket Protocol
WebSocket establishes a full‑duplex communication channel over a single TCP connection. After an HTTP handshake the connection is upgraded, enabling the server to push data to the client.
Handshake Headers
Connection: Upgrade– indicates the client wants to upgrade the protocol. Upgrade: websocket – specifies the target protocol. Sec-WebSocket-Key – random base64 value; the server concatenates it with the GUID 258EAFA5‑E914‑47DA‑95CA‑C5AB0DC85B11, hashes with SHA‑1, and returns the result in Sec-WebSocket-Accept. Sec-WebSocket-Version: 13 – required version defined by RFC 6455. Origin (optional) – the origin of the page initiating the connection.
Server‑Side Setup
Project initialization
mkdir ratchet.websocket.example
cd ratchet.websocket.example
composer require cboden/ratchetWebsocketServer.php
<?php
require __DIR__ . '/vendor/autoload.php';
use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
class WebsocketServer implements \Ratchet\WebSocket\MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})
";
}
public function onMessage(ConnectionInterface $from, MessageInterface $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf(
"Connection %d sending message \"%s\" to %d other connection%s
",
$from->resourceId,
$msg,
$numRecv,
$numRecv == 1 ? '' : 's'
);
foreach ($this->clients as $client) {
$client->send($msg);
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected
";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}
";
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new WebsocketServer()
)
),
8585
);
$server->run();Running the server
php WebsocketServer.phpClient‑Side Example
The HTML page below creates a WebSocket connection to ws://127.0.0.1:8585, sends user input, and displays incoming messages.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Demo</title>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
<h2>WebSocket Demo</h2>
<input type="text" id="data">
<button id="submit" onclick="sub()">Submit</button>
<div id="output"></div>
<script>
var wsUri = "ws://127.0.0.1:8585";
var websocket, output;
function init() {
output = document.getElementById('output');
testWebSocket();
websocket.send('hello
');
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt); };
websocket.onclose = function(evt) { onClose(evt); };
websocket.onmessage = function(evt) { onMessage(evt); };
websocket.onerror = function(evt) { onError(evt); };
}
function onOpen(evt) { writeToScreen('CONNECTED'); }
function onClose(evt) { writeToScreen('DISCONNECTED'); }
function onMessage(evt) {
writeToScreen('RESPONSE: ' + evt.data);
$("#message").append(evt.data);
}
function onError(evt) { writeToScreen('ERROR: ' + evt.data); }
function writeToScreen(message) {
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.innerHTML = message;
output.appendChild(p);
}
function sub() { websocket.send($('#data').val()); }
window.addEventListener('load', init, false);
</script>
</body>
</html>Key Points
The server runs on port 8585 and broadcasts any received message to all connected clients.
The client uses the standard WebSocket API; messages are displayed without page reload.
Ratchet implements MessageComponentInterface to handle connection lifecycle events (open, message, close, error).
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
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.
