π PHP WebSockets – Real-Time Communication
WebSockets allow real-time, two-way communication between a client and a server. Unlike traditional HTTP requests, which require constant polling, WebSockets keep a persistent connection open, making them perfect for live chats, notifications, and multiplayer games. π
π Why Use WebSockets?
- β Instant real-time updates without reloading the page.
- β More efficient than AJAX polling.
- β Ideal for chats, stock prices, notifications, and online games.
π Setting Up a PHP WebSocket Server
Weβll use the Ratchet PHP library to create a WebSocket server.
πΉ Step 1: Install Ratchet
Run the following command to install Ratchet via Composer:
composer require cboden/ratchet
π Example 1: Basic WebSocket Server
Create a file server.php
with the following code:
<?php require 'vendor/autoload.php'; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; use Ratchet\Server\IoServer; use Ratchet\WebSocket\WsServer; class ChatServer implements MessageComponentInterface { protected $clients; public function __construct() { $this->clients = new \SplObjectStorage; } public function onOpen(ConnectionInterface $conn) { $this->clients->attach($conn); echo "New connection! ({$conn->resourceId})\n"; } public function onMessage(ConnectionInterface $from, $msg) { foreach ($this->clients as $client) { if ($client !== $from) { $client->send("User {$from->resourceId}: $msg"); } } } public function onClose(ConnectionInterface $conn) { $this->clients->detach($conn); echo "Connection {$conn->resourceId} closed\n"; } public function onError(ConnectionInterface $conn, \Exception $e) { echo "Error: " . $e->getMessage() . "\n"; $conn->close(); } } $server = IoServer::factory(new WsServer(new ChatServer()), 8080); echo "WebSocket server started on ws://localhost:8080\n"; $server->run(); ?>
π Example 2: WebSocket Client (JavaScript)
Now, let’s create a simple HTML page to connect to the WebSocket server.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket Chat</title> </head> <body> <h2>WebSocket Chat</h2> <input type="text" id="message" placeholder="Type a message..."/> <button onclick="sendMessage()">Send</button> <div id="chatbox"></div> <script> let socket = new WebSocket("ws://localhost:8080"); socket.onmessage = function(event) { let chatbox = document.getElementById("chatbox"); chatbox.innerHTML += "<p>" + event.data + "</p>"; }; function sendMessage() { let message = document.getElementById("message").value; socket.send(message); document.getElementById("message").value = ""; } </script> </body> </html>
π― Summary
- β WebSockets provide real-time, persistent connections.
- β Ratchet PHP is a great library for building WebSocket servers.
- β WebSockets are faster and more efficient than AJAX polling.
π Next Steps
Try extending this example by adding usernames, private messages, or notifications! Happy coding! π