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
What Is New In Laravel 9 - Features Of Laravel 9
What Is New In Laravel 9 - Fea...

In this article, we will see what is new in laravel 9 and the features of laravel 9. Laravel 9 is recently released...

Read More

Feb-13-2022

Laravel 8 Authentication using Jetstream Example
Laravel 8 Authentication using...

In this article, we will discuss laravel 8 authentication with jetstream. This post will give you a simpl...

Read More

Nov-12-2020

Laravel 9 Vue JS CRUD Operation Example
Laravel 9 Vue JS CRUD Operatio...

In this article, we will see the laravel 9 vue js crud operation example. Here, we will learn how to create a vue 3...

Read More

Dec-07-2022

Laravel 8 One To One Relationship Example
Laravel 8 One To One Relations...

In this example we will see laravel 8 one to one relationship example also you can use one to one relationship in l...

Read More

Nov-01-2021