PHP WebSockets

πŸ”Œ 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();
?>

Try It Now


πŸ“ 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>

Try It Now


🎯 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! πŸŽ‰