Ratchet Library for WebSocket in PHP
In modern web development, real-time data exchange is increasingly required: chats, notifications, online games, collaborative document editing. Traditional HTTP is not suitable for such tasks because it operates on a "request-response" model. The WebSocket protocol comes to the rescue, establishing a persistent two-way connection between the client and server.
For PHP, one of the most popular and mature libraries for working with WebSocket is Ratchet. It provides a convenient API for creating WebSocket servers that can handle many simultaneous connections. In this article, we will thoroughly cover how to install Ratchet, write a simple server and client, and look at typical use cases.
What is Ratchet?
Ratchet is a PHP library built on top of ReactPHP (an asynchronous event loop). It allows you to create WebSocket servers that work in real-time without the need for additional modules (like ext-sockets or ext-event). The library supports the RFC 6455 standard (WebSocket) and integrates easily with any PHP application.
Key features of Ratchet:
- Support for the WebSocket protocol (versions 13 and below).
- Ability to create custom controllers for handling messages.
- Built-in support for WAMP (WebSocket Application Messaging Protocol) for pub/sub (publisher-subscriber) and RPC (Remote Procedure Call).
- Easy integration with frameworks (Laravel, Symfony) via separate packages.
- High performance thanks to ReactPHP's asynchronous architecture.
Installing Ratchet
Installation is done via Composer. To do this, run the following command in the root of your project:
composer require cboden/ratchetAfter installation, a vendor directory will appear in your project containing the library and its dependencies (including ReactPHP). Make sure you have PHP version 7.1 or higher installed.
Creating a Simple WebSocket Server
Let's write a simple server that receives messages from clients and sends them back (echo server). Create a file server.php:
<?phprequire __DIR__ . '/vendor/autoload.php';
use Ratchet\\MessageComponentInterface;use Ratchet\\ConnectionInterface;use Ratchet\\Server\\IoServer;use Ratchet\\Http\\HttpServer;use Ratchet\\WebSocket\\WsServer;
class EchoServer implements MessageComponentInterface { public function onOpen(ConnectionInterface $conn) { echo "New connection: {$conn->resourceId}"; }
public function onMessage(ConnectionInterface $from, $msg) { echo "Received message from {$from->resourceId}: {$msg}"; // Send the message back to the sender $from->send("Echo: {$msg}"); }
public function onClose(ConnectionInterface $conn) { echo "Connection {$conn->resourceId} closed"; }
public function onError(ConnectionInterface $conn, \\Exception $e) { echo "Error: {$e->getMessage()}"; $conn->close(); }}
// Start the server on port 8080$server = IoServer::factory( new HttpServer( new WsServer( new EchoServer() ) ), 8080);
echo "WebSocket server started on port 8080";$server->run();Start the server with the command php server.php. It will listen for incoming WebSocket connections on port 8080.
Creating a Client (JavaScript)
For testing, create a simple HTML file with a JavaScript client:
<!DOCTYPE html><html><head> <title>WebSocket Client</title></head><bod Also in library
JWT Tokens in Go (Golang): Creation and Verification with Examples
CLI frameworks for Kotlin: creating console applications
Authorization and Authentication in C++: Libraries, Examples, and Implementation
Swift Task Scheduler: GCD, OperationQueue and Timer on iOS/macOS