Backend Development 7 min read

Implementing WebSocket Communication in PHP with Ratchet

This tutorial explains how to use the Ratchet library to create a PHP WebSocket server, covering environment setup, Composer installation, server-side code, a simple HTML/JavaScript client, and steps to run and test real‑time data transmission.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Implementing WebSocket Communication in PHP with Ratchet

In web application development, real‑time data transfer is essential; the HTTP request‑response model cannot satisfy this need, so the WebSocket protocol is used.

WebSocket provides full‑duplex communication over a single TCP connection, offering faster data transfer and push capabilities, and is widely adopted in real‑time applications.

To implement WebSocket communication in PHP, the Ratchet library can be used. The article outlines the required environment (PHP ≥ 7.0 and Composer) and shows how to install Ratchet via Composer.

Installation command:

composer require cboden/ratchet

After installation, a sample server class MyWebSocketServer implementing MessageComponentInterface is created, with the four required methods onOpen , onMessage , onClose , and onError . The server is then started using Ratchet’s WsServer and ReactPHP components.

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
require 'vendor/autoload.php';
class MyWebSocketServer implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "[New connection] - Connection ID: {$conn->resourceId}\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "[Connection closed] - Connection ID: {$conn->resourceId}\n";
}
public function onError(ConnectionInterface $conn, Exception $e) {
echo "[Error] - Connection ID: {$conn->resourceId} - {$e->getMessage()}\n";
$conn->close();
}
}
$server = new Ratchet\Server\IoServer(new Ratchet\Http\HttpServer(new Ratchet\WebSocket\WsServer(new MyWebSocketServer())));
echo "WebSocket server is running...\n";
$server->run();

A simple front‑end client page is provided to test the server. The HTML page creates a WebSocket object pointing to ws://localhost:8080 , registers an onmessage handler to log received messages, and includes an input field and button to send messages.

<!DOCTYPE html>
<html>
<head>
<title>WebSocket Client</title>
<script>
var socket = new WebSocket("ws://localhost:8080");
socket.onmessage = function(event) {
var message = event.data;
console.log(message);
};
function sendMessage() {
var message = document.getElementById('message').value;
socket.send(message);
}
</script>
</head>
<body>
<input type="text" id="message" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
</body>
</html>

Running the PHP script starts the WebSocket server; opening the HTML page in a browser allows the user to type messages and click Send, with received messages displayed in the browser console, demonstrating real‑time communication.

Conclusion: By using the WebSocket protocol and the Ratchet library, PHP developers can easily add efficient real‑time data transfer to their applications, and the provided example and best practices help quickly get started.

Backendreal-timeWebSocketTutorialRatchetphp-websocket
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

login 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.