In this tutorial, I'll walk you through the process of building a custom WebSocket server using Laravel 11 and Ratchet. While many tutorials focus on Laravel Echo for real-time communication, we'll explore how to set up a WebSocket server from scratch with Ratchet, a PHP library for WebSockets.
This guide is designed for developers who want full control over their WebSocket implementation in Laravel without relying on third-party services.
Step-by-Step Guide to Building a Custom WebSocket Server with Laravel and Ratchet
If you haven’t already, start by installing Laravel 11 using Composer. Run the following command to create a fresh Laravel project:
composer create-project --prefer-dist laravel/laravel websocket-server
Next, you’ll need to install Ratchet and a few other dependencies to handle WebSockets. Run this command to install Ratchet:
composer require cboden/ratchet
We'll also use symfony/process
to easily manage the WebSocket server from within Laravel:
composer require symfony/process
Now, let's create a WebSocket server class that will handle incoming connections, messages, and disconnections.
<?php
namespace App\WebSocket;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class WebSocketServer 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 ($from !== $client) {
$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 has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
This class will manage all client connections. When a new connection opens, it's added to the $clients
storage. Messages sent by clients are broadcasted to all other clients, and disconnections are handled by detaching the client.
We need a command to run the WebSocket server. In Laravel, you can do this by creating an Artisan command.
Run the following Artisan command to create it:
php artisan make:command WebSocketServer
Then update the generated file in app/Console/Commands/WebSocketServer.php:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\Server\IoServer;
use App\WebSocket\WebSocketServer;
class WebSocketServerCommand extends Command
{
protected $signature = 'websocket:serve';
protected $description = 'Start the WebSocket server';
public function handle()
{
$server = IoServer::factory(
new HttpServer(
new WsServer(
new WebSocketServer()
)
),
8080
);
$this->info("WebSocket server started on port 8080");
$server->run();
}
}
This command starts the WebSocket server on port 8080
. Running this command will listen for WebSocket connections.
Now that the WebSocket server is ready, you can run it using Artisan:
php artisan websocket:serve
When the server is running, it will start listening on port 8080. You can now connect to this WebSocket server from a client.
To test your WebSocket server, you can create a simple HTML page with JavaScript to connect to the server.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Client - Websolutionstuff</title>
</head>
<body>
<h1>WebSocket Client</h1>
<input type="text" id="message" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
<script>
let ws = new WebSocket('ws://localhost:8080');
ws.onopen = function() {
console.log('Connected to WebSocket server');
};
ws.onmessage = function(event) {
console.log('Message from server: ' + event.data);
};
function sendMessage() {
const message = document.getElementById('message').value;
ws.send(message);
}
</script>
</body>
</html>
This HTML file connects to the WebSocket server on ws://localhost:8080
, allowing you to send and receive messages.
Open your browser and navigate to the HTML file. Open the browser console to see WebSocket events. Type a message and hit "Send"—you’ll see the message in the console and broadcast to other clients if multiple clients are connected.
You might also like:
In this article, we will see how to add an index in laravel 10 migration. Here, we will learn about the laravel 10...
May-03-2023
In this article, we will fix the laravel 9 form class not found error, many times we have received errors like lara...
Sep-19-2022
In our ever-changing digital landscape, staying ahead of the competition is essential. And that's precisely what we&...
Jan-11-2023
In this tutorial i will show you how to login with mobile number in laravel using Laravel Custom Auth , laravel pro...
Jun-18-2021