Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

xingfucoder's avatar

Hoa\WebSocket with Laravel 5 Projects - Push notifications

Using the Hoa\Websocket Package within Laravel 5 Projects for Server-Client push notifications

Installation

To use the Hoa\Websocket package with your Laravel 5 Projects you need to add that package to the Composer.json file or use the composer require command.

This is the composer require sentence:

{
    "require": {
        "hoa/websocket": "~2.0"
    }
}

For more information go to the next link: HoaProject\WebSocket Github Repository

The next step is create the Server file.

You may use a custom root file within your app folder as follow:

app\server.php

The content of this file will be:

<?php
/*Create a server variable with the link to the tcp IP and custom port you need to
specify the Homestead IP if you are using homestead or, for local environment using
WAMP, MAMP, ... use 127.0.0..1*/

$server = new Hoa\Websocket\Server(
    new Hoa\Socket\Server('tcp://192.168.10.10:8889')
);

//Manages the message event to get send data for each client using the broadcast method
$server->on('message', function ( Hoa\Core\Event\Bucket $bucket ) {
    $data = $bucket->getData();
    echo 'message: ', $data['message'], "\n";
    $bucket->getSource()->broadcast($data['message']);
    return;
});
//Execute the server
$server->run();

You should execute this file within your Server Host to begin the process. Then you need to manage the Client code.

Create a custom view, for instance you may create the following file:

resources\views\client.blade.php

You could put the next code within this file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel 5 | WebSockets</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">
    <div class="row ">
        <div class="col-xs-12">
            <br/>
            <input type="text" id="input" placeholder="Message…"/>
            <hr/>
            <pre id="messages">
            </pre>
        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script>
    //The homestead or local host server (don't forget the ws prefix)
    var host = 'ws://192.168.10.10:8889';
    var socket = null;
    var input = document.getElementById('input');
    var messages = document.getElementById('messages');
    var print = function (message) {
        var samp = document.createElement('samp');
        samp.innerHTML = '\n' + message + '\n';
        messages.appendChild(samp);
        return;
    };

    //Manges the keyup event
    input.addEventListener('keyup', function (evt) {
        if (13 === evt.keyCode) {
            var msg = input.value;
            if (!msg)
                return;
            try {
                //Send the message to the socket
                socket.send(msg);
                input.value = '';
                input.focus();
            } catch (e) {
                console.log(e);
            }
                print(msg);
            return;
        }
    });

    try {
        socket = new WebSocket(host);
        
        //Manages the open event within your client code
        socket.onopen = function () {
            print('Connection Opened');
            input.focus();
            return;
        };
        //Manages the message event within your client code
        socket.onmessage = function (msg) {
            print(msg.data);
            return;
        };
        //Manages the close event within your client code
        socket.onclose = function () {
            print('Connection Closed');
            return;
        };
    } catch (e) {
        console.log(e);
    }
</script>
</body>
</html>

Put the Server to work

The next step is start the server. You need to go to the CLI and use the following command:

    //If your server file is located within the root folder
    php app\server.php

Then open two clients (before this step you need to create the custom route to load the previous view), for instance, a Google Chrome tab, and a Mozilla Firefox tab with your custom domain server. You may view within each client windows the connection opened message. Next tip any message, and you will view those within each client and the CLI Server windows.

If you exit from your server you will view the Connection Closed message within ech of the client windows.

More info

If you want to view more info about that package, go to the next link:

Hoa\WebSocket Project Documentation

Hope it helps you.

0 likes
16 replies
constb's avatar

@codeatbusiness neat. Although your example only covers interaction between clients. How do I make websocket server interact with a laravel application? How do I publish messages from a Controller? How do I turn a received message into an Event?

1 like
xingfucoder's avatar

Yeah @constb I only tried this package yesterday and then put the example here. I'm working on that to view all integration process.

I think is so easy to interact with a Laravel 5 application because you are working with events and with this Event Feature of Laravel 5 I think wouldn't be difficult this integration.

You can find more info within the official documentation of Hoa Websocket about the client communication process.

For the event management you may view the next line:

//Socket server message event
$server->on('message', function() {
     //Fire your Laravel Event here
});

You always need to are running your server before that.

constb's avatar

@codeatbusiness I see possible problem in the fact that WS server is running permanently. If I bootstrap laravel application kernel inside it and open a database connection - there's no guarantee the connection won't expire and be closed remotely by database (like, on a timeout). That's the same issue as with artisan queue:work --daemon vs. artisan queue:listen.

I think bulletproof solution would be to trigger custom artisan commands there and have all event firing and handling managed in a separate process with it's own ConsoleKernel bootstrapped. Like queue:listen does. The one problem here is how do you transfer message payload from WS server to an artisan command. The other is what to do is there's a LOT of messaging going on, because bootstrapping an application takes time and cpu resources.

xingfucoder's avatar

Hi @constb I think you may use a server process to verify if the server is running and if that is not running proceed to start it. I think to have the server running with this process would not be a problem in production, the problem would be the stop of the process without advise us. Then for this event, you have the socket.onclose event, you then may need to restart your server when this event was fired. Create a custom event for this reason and manage the restarting process.

constb's avatar

@codeatbusiness actually starting and stopping is not a problem. People have been running laravel's queue listener through supervisor package like forever. It's simple and it restarts process if it dies automatically.

ps. Really good piece of code, by the way. Writing websocket server without Ratchet that's quite impressive.

1 like
xingfucoder's avatar

Hi @jeffreyWay, I think would be very useful get a lesson for the integration of that package with Laravel 5.

It is a great client-server messaging package that works nicely, and with the Laravel 5 Events may open great fields of application.

xingfucoder's avatar

@constb, I'm still using artisan commands for manage the Websocket server but I think that using envoy or ssh capabilities, or the supervisor package that you commented here may be fine.

The problem is when you need to send a message from the server to the clients. That message is not sent.

constb's avatar

@codeatbusiness sorry, the way you started the topic made me think you're the author of this package. I took a closer look at it and I'm not sure what is the best way to implement server-to-clients communication. When client sends a message triggering artisan command on server is obvious solution. But the reverse requires some sort of queue that WS-server must poll for new server-to-clients messages and add them to internal send-queue. On laravel side it's simple - laravel allows multiple named queues, we can add special websocket-messaging queue, but Hoa\Websocket has no way of executing code (like queue polling) while its idle. At least I didn't manage to find one. Maybe this should be added as a feature request there.

zefman's avatar

I implemented realtime messaging in a Laravel app recently using web sockets and found the best, way to interact between the socket server and the Laravel app was to use a shared redis database.

In my case I used node for the websocket server but it would work the same either way. In Laravel I do something like,

    $redis = \RedisL5::connection();
        $redis->publish( 'messaging', json_encode( [
            'conversation_id' => $conversation->id,
            'participants'    => $participants,
            'message'         => $message
        ] ) );

Then on websocket server you can subscribe to the redis channel, and push the messages, notifications or whatever you like on the clients. In node its something like this:

    // Subscribe to the redis messaging channel
        redisClient.subscribe( 'messaging', 'conversation' );

        redisClient.on( 'message', function( channel, data ) {

            data = JSON.parse( data );

        client.emit( channel, data );
    } );
NoorDeen's avatar

hi every body . any news about this great package ? did any one wrote integration package to use with laravel 5 event broadcasting ?

vikram5845's avatar

Hey guys When I try execute the app/server.php file I get following error

Hoa\Websocket\Server not found on line 5 .

So then I put the require_once(app_path().'../vendor/hoa/websocket/server.php'); and now I am getting error as

Class 'Hoa\Websocket\Connection' not found

Some one please help me out

1 like
afoantwi's avatar

instead of require_once(app_path().'../vendor/hoa/websocket/server.php');

do

require_once(DIR.'/../vendor/autoload.php');

begin and end 'DIR' with two underscores!

Ashutosh's avatar

For laravel Change this line $server->on('message', function ( Hoa\Core\Event\Bucket $bucket ) to $server->on('message', function ( Hoa\Event\Bucket $bucket )

Ashutosh's avatar

@vikram5845 use this line require_once(DIR.'/../vendor/autoload.php'); Please mark here (UnderscoreUnderscoreDIRunderscoreUnderscore)

jpacareu's avatar

@vikram5845 I had the same problem but when I added the require_once line, the CLI says:

#root@lvs laravel/app# php server.php

PHP Fatal error: Class 'Hoa\Websocket\Server' not found in /var/www/laravel/app/server.php on line 7 PHP Stack trace: PHP 1. {main}() /var/www/laravel/app/server.php:0

this is my server.php code:

<?php
/*Create a server variable with the link to the tcp IP and custom port you need to
specify the Homestead IP if you are using homestead or, for local environment using
WAMP, MAMP, ... use 127.0.0..1*/
require_once(__DIR__.'/../vendor/autoload.php');

$server = new Hoa\Websocket\Server(
    new Hoa\Socket\Server('tcp://192.168.3.119')
);

//Manages the message event to get send data for each client using the broadcast method
$server->on('message', function ( Hoa\Core\Event\Bucket $bucket ) {
    $data = $bucket->getData();
    echo 'message: ', $data['message'], "\n";
    $bucket->getSource()->broadcast($data['message']);
    return;
});
//Execute the server
$server->run();

Please guys help me on this!

jpacareu's avatar

The problem was solved when executed composer install command (properly) on the host, but now I'm having this response from the CLI:

PHP Fatal error:  Uncaught Hoa\Socket\Server::_open(): (1) Server cannot join tcp://192.168.3.119/ and returns an error (number 0): Failed to parse address "192.168.3.119/".
in /var/www/laravel/vendor/hoa/socket/Server.php at line 239.
  thrown in /var/www/laravel/vendor/hoa/socket/Server.php on line 239

Please or to participate in this conversation.