Real-Time
Ratchet WebSockets
Create real-time, bi-directional applications easily. Prisma PHP automates the Ratchet server setup and includes auto-refresh, letting you focus on building chat systems, dashboards, and collaborative tools.
Server Setup
Prerequisite
You must select "WebSocket" during the project creation wizard to have these files scaffolded automatically.
This configures Ratchet's IoServer, HttpServer, and WsServer components.
src/lib/websocket/server.php
require __DIR__ . '/../../../vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Lib\Websocket\ConnectionManager;
$server = IoServer::factory(
new HttpServer(
new WsServer(
new ConnectionManager()
)
),
8080
);
$server->run();
Connection Management
The ConnectionManager handles the lifecycle of WebSocket connections, messaging, and error states.
src/lib/websocket/ConnectionManager.php
namespace Lib\Websocket;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Exception;
use SplObjectStorage;
class ConnectionManager implements MessageComponentInterface {
protected SplObjectStorage $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) {
// Handle incoming messages
}
public function onClose(ConnectionInterface $conn) {
// Handle disconnection
}
public function onError(ConnectionInterface $conn, Exception $e) {
// Handle errors
}
}
Client-Side Implementation
Connect to your WebSocket server using the native browser API.
src/app/js/index.js
const ws = new WebSocket("ws://localhost:8080");
ws.onopen = function(event) {
console.log("Connected to the WebSocket server");
};
ws.onmessage = function(event) {
// Handle incoming messages
};
document.getElementById('messageForm').addEventListener('submit', function(event) {
event.preventDefault();
// Form submission logic
});