Building a Custom WebSocket Server with Laravel 11 and Ratchet

Websolutionstuff | Sep-23-2024 | Categories : Laravel

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

Step-by-Step Guide to Building a Custom WebSocket Server with Laravel and Ratchet

 

Step 1: Install Laravel 11

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

 

Step 2: Install Ratchet and Required Dependencies

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

 

Step 3: Create WebSocket Server Class

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.

 

Step 4: Create WebSocket Command

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.

 

Step 5: Running the WebSocket Server

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.

 

Step 6: Creating the Frontend 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.

 

Step 7: Testing the WebSocket Server

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:

Recommended Post
Featured Post
How To Add Index In Laravel 10 Migration
How To Add Index In Laravel 10...

In this article, we will see how to add an index in laravel 10 migration. Here, we will learn about the laravel 10...

Read More

May-03-2023

Laravel 9 Form Class Not Found
Laravel 9 Form Class Not Found

In this article, we will fix the laravel 9 form class not found error, many times we have received errors like lara...

Read More

Sep-19-2022

Laravel 10: New Features And Release Date
Laravel 10: New Features And R...

In our ever-changing digital landscape, staying ahead of the competition is essential. And that's precisely what we&...

Read More

Jan-11-2023

Login with Mobile Number using Laravel Custom Auth
Login with Mobile Number using...

In this tutorial i will show you how to login with mobile number in laravel using Laravel Custom Auth , laravel pro...

Read More

Jun-18-2021