Step-by-Step Guide to Creating a PHP WebSocket Server: Real-Time Communication Simplified
Thus, by creating a PHP Websocket server, you can create your web applications that work in real-time mode, such as chat applications, live notifications, multi-player games, etc. This form of communication is always open between the client and the server, making it great for two-way communication because it offers both ends the power to send data to each other.
Install WebSocket PHP Library
Yet, some libraries may be utilized to implement WebSocket functionality into PHP applications. One such popular library is Ratchet; this library is quite effective in providing easier ways to build real-time WebSocket apps.
To install Ratchet, carry out the following steps:
- First, you should have Composer installed (the PHP dependency manager).
- Then create a new project directory and go in it.
- Now execute this command: to install the needed libraries.
composer require cboden/ratchet
Create the WebSocket Server
Then you can start building the WebSocket server, as Ratchet has already been installed. Here is a very simple example of a WebSocket server:
Create a file server.php:
<?php require dirname(__DIR__) . '/vendor/autoload.php'; // Include Ratchet's autoload use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class MyWebSocketServer implements MessageComponentInterface { // Array to hold all the connections (clients) protected $clients; public function __construct() { $this->clients = new \SplObjectStorage; } // Called when a new connection is made public function onOpen(ConnectionInterface $conn) { // Add the connection to the $clients array $this->clients->attach($conn); echo "New connection! ({$conn->resourceId})\n"; } // Called when a message is received from a client public function onMessage(ConnectionInterface $from, $msg) { echo "Message from ({$from->resourceId}): $msg\n"; // Send the message to all connected clients foreach ($this->clients as $client) { if ($from !== $client) { // Don't send the message to the sender $client->send($msg); } } } // Called when a connection is closed public function onClose(ConnectionInterface $conn) { $this->clients->detach($conn); echo "Connection {$conn->resourceId} has disconnected\n"; } // Called if an error occurs public function onError(ConnectionInterface $conn, \Exception $e) { echo "Error: {$e->getMessage()}\n"; $conn->close(); } } // Create the WebSocket server and listen on port 8080 $server = IoServer::factory( new HttpServer( new WsServer( new MyWebSocketServer() ) ), 8080 ); // Start the server $server->run();
- MyWebSocketServer : Implements
MessageComponentInterface
, which requires four methods:onOpen
,onMessage
,onClose
, andonError
. - onOpen : Triggered when a new connection is established.
- onMessage : Triggered when a message is received from a client, which is broadcasted to all other clients (except the sender).
- onClose : Triggered when a client disconnects.
- onError : Triggered when an error occurs.
Running the Server
php server.php
Creating the WebSocket Client Using HTML + JavaScript
Now, you need a client-side application that connects to the WebSocket server. Create an index.html
file with the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket Client</title> <style> #messages { border: 1px solid #000; padding: 10px; height: 200px; overflow-y: auto; } </style> </head> <body> <h2>WebSocket Chat</h2> <div id="messages"></div> <input type="text" id="messageInput" placeholder="Type a message..." /> <button onclick="sendMessage()">Send</button> <script> const socket = new WebSocket('ws://localhost:8080'); socket.onopen = () => { console.log("Connected to WebSocket server"); }; socket.onmessage = (event) => { const messagesDiv = document.getElementById('messages'); const message = document.createElement('div'); message.textContent = event.data; messagesDiv.appendChild(message); }; socket.onerror = (error) => { console.error("WebSocket error:", error); }; socket.onclose = () => { console.log("Connection closed"); }; function sendMessage() { const messageInput = document.getElementById('messageInput'); const message = messageInput.value; socket.send(message); messageInput.value = ''; // Clear the input field } </script> </body> </html>
Conclusion
A very simple tutorial to help you create a simple PHP WebSocket Server and Client using Ratchet. To make instant, fully duplex communication possible, WebSockets are used in modern web applications such as live chat, notifications, multiplayer games, etc.
Leave a Reply