How to Build a WebSocket Chat Server with PHP and Ratchet
This tutorial explains how to set up a real‑time chat application by installing the Ratchet library with Composer, creating a PHP WebSocket server, launching it, and building a simple HTML/JavaScript client that connects to ws://localhost:8080 to exchange messages instantly.
WebSocket is a full‑duplex communication protocol suitable for real‑time scenarios such as instant messaging and live data updates. PHP, as a popular server‑side language, can implement WebSocket functionality using appropriate libraries and extensions.
Install Ratchet Library
Use Composer to add the Ratchet library to your project:
<code>composer require cboden/ratchet</code>Create WebSocket Server
Create a server.php file in the project root and add the following code:
<code><?php
require __DIR__.'/vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
class Chat 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($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, Exception $e) {
echo "An error occurred: {$e->getMessage()}\n";
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
echo "Server running at http://localhost:8080\n";
$server->run();
</code>Start WebSocket Server
From the project root, run the following command to launch the server:
<code>php -f server.php</code>The server will listen on port 8080 and can be accessed via http://localhost:8080 .
Write Front‑End Page
Create an index.html file in the project directory with this content:
<code><!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
<script>
var socket = new WebSocket("ws://localhost:8080");
socket.onopen = function(event) {
console.log("Socket opened");
};
socket.onmessage = function(event) {
console.log("Message received: " + event.data);
};
socket.onclose = function(event) {
console.log("Socket closed");
};
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>
</code>Open index.html in a browser; you will see an input box and a Send button. Typing a message and clicking Send transmits it to the server.
Test the Application
Open multiple browser windows or tabs, enter different messages, and click Send. Each message is broadcast to all connected clients.
By following these steps, you have built a simple PHP WebSocket server that enables real‑time chat functionality using the Ratchet library.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.