Websockets for Laravel. Done right.

Last update: May 22, 2022

Laravel WebSockets 🛰

Latest Version on Packagist GitHub Workflow Status Quality Score Total Downloads

Bring the power of WebSockets to your Laravel application. Drop-in Pusher replacement, SSL support, Laravel Echo support and a debug dashboard are just some of its features.

https://phppackagedevelopment.com

If you want to learn how to create reusable PHP packages yourself, take a look at my upcoming PHP Package Development video course.

Documentation

For installation instructions, in-depth usage and deployment details, please take a look at the official documentation.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

GitHub

https://github.com/beyondcode/laravel-websockets
Comments
  • 1. [2.x] Major refactoring

    Rewritten from scratch

    The project got re-written from scratch as stated the reasons in https://github.com/beyondcode/laravel-websockets/pull/519

    The contributors are going to remain the same, including @francislavoie with the awesome starting point to horizontally-scale the running servers.

    Rewrite changelog

    • The migration file suffered a small modification. Run vendor:publish to get the second migration file that changes the fields to plural.
    • The configuration file got itself re-written as well with simplicity in mind (the initial 2.x was still a mess). Get a new copy of it.
    • Interfaces moved to Beyondcode\LaravelWebSockets\Contracts\*. If you extend certain functionalities, makes sure to use the right namespaced interfaces.
    • The replication driver is now called replication mode. Env's WEBSOCKETS_REPLICATION_MODE variable now can be set to local or redis.
    • Replicators got merged into Channel Managers. If you added your own custom replicator, you now should implement the BeyondCode\LaravelWebSockets\Contracts\ChannelManager interface.
    • Statistics Loggers are now called Statistics Collectors. Their job is to temporarily store the data between dumps into the database (by default).
    • Handlers for the WebSocket, as well as the HTTP API Server, got re-written. They are still found in the config, but make sure to check them if you extend one of them.
    • The vast majority functions of the channel managers now use PromiseInterfaces for consistencies. This means that instead of returning int or strings, you may now return a FulfilledPromise($value) to easily get resolved. If you don't implement your own channel manager (or now defunct, replicator), it's totally fine.
    • Presence channels now properly trigger the .here() methods.
    • Dashboard got broadcasting fixes. If you still encounter issues with sending events from the dashboard, open an issue.

    Pre-Rewrite changelog

    • [x] Restructured the config file (https://github.com/beyondcode/laravel-websockets/pull/446)
    • [x] ~Redis PubSub driver support for Horizontally-scaled WebSocket servers (https://github.com/beyondcode/laravel-websockets/pull/140, https://github.com/beyondcode/laravel-websockets/pull/448, https://github.com/beyondcode/laravel-websockets/pull/477, https://github.com/beyondcode/laravel-websockets/commit/5b6bdf49e46eead770d8cbab0ed7db53849561f3)~ Rewritten, Channel Managers now do all the jobs on tracking the channels and connections
    • [x] Rename the AppProvider to AppManager to avoid conflicts with Larave's App Providers (https://github.com/beyondcode/laravel-websockets/pull/451)
    • [x] Remove Laravel 5.8.x (https://github.com/beyondcode/laravel-websockets/pull/452)
    • [x] ~Extendable hooks as in https://github.com/beyondcode/laravel-websockets/issues/80 (https://github.com/beyondcode/laravel-websockets/pull/465, https://github.com/beyondcode/laravel-websockets/commit/3e239a0728bb37f613e5abe7015843cd089669cb)~ The extendable hooks' place in config file got changed. Get a new copy of the config file.
    • [x] Refactor dashboard with Tailwind (https://github.com/beyondcode/laravel-websockets/pull/467)
    • [x] Add per-app CORS settings (https://github.com/beyondcode/laravel-websockets/pull/469)
    • [x] ~Docblocks (https://github.com/beyondcode/laravel-websockets/pull/471)~ Rewritten from scratch.
    • [x] ~Custom statistics loggers (including the already-provided Database using ORM) (https://github.com/beyondcode/laravel-websockets/pull/473, https://github.com/beyondcode/laravel-websockets/pull/482/commits/714cc5b22def3da5f1ef8da23b2c89cd0af42d87, https://github.com/beyondcode/laravel-websockets/pull/482/commits/108a717c0af82f5f04e8164a13211b3c36dcc401)~ Statistics Loggers now are called Statistics Collectors and their job is to store the data temporarily between dumps. When the amount of time in seconds pass, they are dumped into a Statistics Store. Defaults to Database.
    • [x] ~More use cases tests (https://github.com/beyondcode/laravel-websockets/pull/450, https://github.com/beyondcode/laravel-websockets/pull/453, https://github.com/beyondcode/laravel-websockets/pull/464, https://github.com/beyondcode/laravel-websockets/pull/482)~ TDD-ed the entire project while keeping in mind the functionality tests.
    • [x] Update docs to reflect changes (https://github.com/beyondcode/laravel-websockets/pull/468)
      • [x] Using WebSockets with Cloudflare (does not support 6001 as default port)
      • [x] Setting up the websockets broadcaster for the horizontal scaling function
      • [x] Restarting the server with websockets:restart
    Reviewed by rennokki at 2020-08-13 10:43
  • 2. Multiple App Servers & Load Balancer Help

    Hello, I'm just after clarification or pointers on how best to approach laravel-websockets with my setup. I run all my servers under Laravel Forge and I use their load balancers which is a Nginx server with a reverse proxy.

    My setup is 1 load balancer, 4 app servers (same codebase), a dedicated MySQL and a dedicated Redis server. Previously I ran Laravel Echo Server on the same server as the Redis DB and the 4 app servers were able to communicate, however my project now needs sockets on mobile which lead me here due to the Pusher SDK implementation.

    I'm wondering how best to deploy laravel-websockets with my app. Should I run a dedicated server instance with only laravel-websockets and proxy all 4 servers there so there's a single websockets server on a subdomain or should each of the 4 app servers be running websockets:serve ?

    I do intend to use Redis once v2 is ready, however I am still wondering which of the 2 solutions would be best?

    Reviewed by AugmentBLU at 2020-09-10 17:52
  • 3. Redis as a replication backend for scalability

    This is a continuation of @snellingio's work in #61 and supersedes it.

    Disclaimer: this is still WIP, I still have some work to do here before it's ready to go.

    Things that are done:

    • Some general cleanup I fixed some typos here and there, added some additional type hints to make my IDE happy, added @mixin on Facades, etc.
    • Rewrote RedisClient to use lazy clients (thanks @WyriHaximus for implementing that feature!) and implemented pub/sub.
    • If client push is enabled, that should also work, via publishing to Redis. RedisClient will ignore messages from itself.
    • RedisPusherBroadcaster is implemented. This is a hybrid of the Redis and Pusher broadcasters that are shipped with Laravel. This is needed because we still want to use the Pusher auth logic (signing the broadcasted messages) but we want to broadcast via Redis instead of doing an HTTP request to the websocket server to push out messages.
    • Pub/sub logic is implemented under a feature flag in config, it gets checked at every entry-point into replication logic. This means that nothing should change for users that don't need replication
    • Scope the pub/sub channels on Redis by app ID This is needed so that channels from different apps don't cross-talk when they aren't supposed to. This is done in the Broadcaster and RedisClient. Redis channels are names "$appId:$channel" wherever needed.
    • Implement storing Presence Channel information in Redis This one was tricky, because among other things, it required rewriting some of the HTTP controller logic to support Redis' async IO. The replication feature flag complicates this a bit as well because we end up with two code paths throughout, wherever it's enabled. I'll probably need the most help reviewing this portion due to its complexity.
    • Tests I went the route of extending some of the existing tests, only running the tests with replication enabled as well, to hit the relevant code paths. RedisClient is not covered, a LocalClient mock is used instead.
    • Just a note: I found that it doesn't make sense to put any of the logic in the channel manager (e.g. RedisChannelManager) because it doesn't itself do anything. Channel and PresenceChannel are where the interesting things happen. Maybe these classes could be split up into replicated versions of each, but it doesn't seem entirely necessary yet.

    Things that are still to do:

    • Improve reliability via Redis reconnect logic In case Redis goes down, RedisClient should attempt to reconnect, and if successful, should re-subscribe to all the channels on behalf of the users. This shouldn't be too hard, there's already local storage for the list of channels (see protected $subscribedChannels in RedisClient)
    • Documentation We'll need new sections in the documentation to describe how to set this up. Notably, users will need to add a new driver in broadcasting.php due to the hybrid broadcaster I implemented.
    Reviewed by francislavoie at 2019-03-25 22:35
  • 4. WebSocket connection to 'wss://mydomain:6001/app/1234567890?protocol=7&client=js&version=5.0.2&flash=false' failed: Error in connection establishment: net::ERR_SSL_VERSION_OR_CIPHER_MISMATCH

    I'm getting this error. Its killing my time. I dig deep and found no proper solution for this issue. in **LOCAL SERVER its working fine **. but in LIVE SERVER this issue arises.

    I put 'local_pk' and 'local_cert' both path inside websockets.php file

    its my app.js file

    window.Echo = new Echo({ broadcaster: 'pusher', key: '1234567890', wsHost: window.location.hostname, wsPort: 6001, encrypted: false, wssPort: 6001, disableStats: true, enabledTransports: ['ws', 'wss'], });

    here is my broadcasing.hp config

    'connections' => [
    
        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'host' => '127.0.0.1',
                'encrypted' => false,
                'port' => 6001,
                'scheme' => 'https',
                'curl_options' => [
                    CURLOPT_SSL_VERIFYHOST => 0,
                    CURLOPT_SSL_VERIFYPEER => 0,
                ]
            ],
        ],
    

    PLEASE HELP ME OUT.

    Reviewed by fahim152 at 2019-11-07 05:52
  • 5. [Proposal] Change of Websocket implementation

    Hi BeyondCode. Love your stuff.

    Things I don't like is stuff with many issues. Seems that some upstream dependencies are creating a lot of havoc regarding the WebSocket Server.

    There is a pure PHP implementation of WebSockets that uses concurrency, created by the guys of amphp, the same group who figured out Fibers. It seems stable.

    I may create a PR that exchanges the upstream dependencies for that, which may fix a lot of problems thanks to the bloated dependency list.

    Reviewed by DarkGhostHunter at 2021-05-02 01:47
  • 6. Crashed in production, supervisord process was still running

    So basically it stopped working, even though the process in supervisord was showing up as running (since 60 days). After I restarted the process with supervisord it worked again. What could have happened and how could I avoid this in the future?

    Reviewed by Hillcow at 2020-03-02 10:21
  • 7. Invalid auth signature provided Exception

    So I have a search engine built into my app that fetches results from multiple sources from across the web from different engines and broadcasts the results in real-time as we get a response.

    I was using laravel-echo-server earlier and it was all good. I migrated to this package and have been facing this issue. At first, I thought it could be a third-party issue and tested the APIs and everything else but it seems like everything is fine at that end but when it's broadcasting results in a loop, it shows this error for few broadcasts.

    What you think could be breaking the flow and causing this issue? I'm sending JSON payload of results after we've parsed and transformed as per the format we need on the front-end.

    Exception `Symfony\Component\HttpKernel\Exception\HttpException` thrown: `Invalid auth signature provided.`
    
    Reviewed by irazasyed at 2018-12-06 20:16
  • 8. SSL

    Hi There, First of all, thank you for a great plugin.

    I have looked at the other questions regarding SSL and none seem to cover my scenario.

    I am having an issue with Self Signed SSL Certificates. I have created them with this command : openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 I then set the broadcasting.php as follows :

    'pusher' => [
                'driver' => 'pusher',
                'key' => env('PUSHER_APP_KEY'),
                'secret' => env('PUSHER_APP_SECRET'),
                'app_id' => env('PUSHER_APP_ID'),
                'options' => [
                    'cluster' => env('PUSHER_APP_CLUSTER'),
                    'encrypted' => true,
                    'host' => 'sockets.myDomainHere.com',
                    'port' => 6001,
                    'scheme' => 'https',
                    'curl_options' => [
                        CURLOPT_SSL_VERIFYHOST => 0,
                        CURLOPT_SSL_VERIFYPEER => 0,
                    ]
                ],
            ],
    

    I Then Set the websockets.php as follows ( comment removed for size ):

    'ssl' => [ 
            'local_cert' => '/full/path/to/self/signed/cert.cert',
            'local_pk' => '/full/path/to/self/signed/key.key', 
            'passphrase' => 'ThePassphraseIEnteredWhenCreatingTheCertificate',
            'verify_peer' => false,
        ],
    

    On my client I have it as follows :

    new Echo({ 
            auth:{ headers: { 'Authorization': 'Bearer ' + user.token } },
            broadcaster: 'pusher',
            key: '123456',
            wsHost: 'sockets.myDomainHere.com',
            wsPort: 6001,
            wssPort: 6001,
            disableStats: true, 
            enabledTransports: ['ws', 'wss']
        });
    

    So I have 2 issues :

    1. If I go to the Debug Dashboard I cannot connect to the Server ERROR :

    pusher.min.js:8 WebSocket connection to 'ws://sockets.myDomainHere.com:6001/app/123456?protocol=7&client=js&version=4.3.1&flash=false' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

    1. If I go to my app frontend, I get this :

    WebSocket connection to 'wss://sockets.myDomainHere.com:6001/app/123456?protocol=7&client=js&version=4.3.1&flash=false' failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID

    Any feedback will be great, Thanks.

    Reviewed by cbezzy at 2019-02-13 04:52
  • 9. Illuminate \ Broadcasting \ BroadcastException No message

    First of all thank you for your great work.

    I'm using your package for a few days and after some test, I could connect to my dashboard with connection to websocket.

    In next step I create an event name NewQuestion that have a very simple event for test:

    class NewQuestion implements ShouldBroadcast
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;
    
        public $message;
        /**
         * Create a new event instance.
         *
         * @return void
         */
        public function __construct($message)
        {
            $this->message = $message;
        }
    
        /**
         * Get the channels the event should broadcast on.
         *
         * @return \Illuminate\Broadcasting\Channel|array
         */
        public function broadcastOn()
        {
            return new PrivateChannel('moderator');
        }
    }
    

    When I simply call my event after new question store in QuestionController , laravel says:

    Illuminate \ Broadcasting \ BroadcastException No message

    and this is part of laravel report:

       $response = $this->pusher->trigger(
            $this->formatChannels($channels), $event, $payload, $socket, true
        );
    
        if ((is_array($response) && $response['status'] >= 200 && $response['status'] <= 299)
            || $response === true) {
            return;
        }
    
        throw new BroadcastException(
            is_bool($response) ? 'Failed to connect to Pusher.' : $response['body']
        );
    }
    
    /**
     * Get the Pusher SDK instance.
     *
     * @return \Pusher\Pusher
     */
    public function getPusher()
    {
        return $this->pusher;
    }
    

    }

    Would you please let me know what wrong in my case?

    my configurations:

    broadcasting.php:

            'pusher' => [
                'driver' => 'pusher',
                'key' => env('PUSHER_APP_KEY'),
                'secret' => env('PUSHER_APP_SECRET'),
                'app_id' => env('PUSHER_APP_ID'),
                'options' => [
                    'cluster' => env('PUSHER_APP_CLUSTER'),
                    'encrypted' => true,
                    'host' => '127.0.0.1',
                    'port' => 6001,
                    'scheme' => 'https'
                ],
            ],
    

    websockets.php:

        'apps' => [
            [
                'id' => env('PUSHER_APP_ID'),
                'name' => env('APP_NAME'),
                'key' => env('PUSHER_APP_KEY'),
                'secret' => env('PUSHER_APP_SECRET'),
                'enable_client_messages' => false,
                'enable_statistics' => true,
            ],
        ],
    .
    .
    .
              'local_cert' => '/home/myDomain/domains/myDomain.com/private_html/local.cert',
    .
    .
    .
            'local_pk' => '/home/myDomain/domains/myDomain.com/private_html/key.cert',
    .
    .
    .
    
    
    Reviewed by sanjarani at 2019-04-17 06:34
  • 10. Can't get SSL to work

    I've tried following the docs, both the first SSL related sections and the Valet specific settings. I'm running on a cPanel server with Let's Encrypt cert.

    Without HTTPS on the site and "encrypted: true" for Echo, laravel-websockets works fine!

    The websockets.php config file comment says "Path to local certificate file on filesystem. It must be a PEM encoded file which contains your certificate and private key."

    I'm not sure that the file contains both the certificate and private key. Is there a way to check?

    I also tried creating a separate key file on the cPanel server and using that in websockets.php. Not sure if that is supposed to work. Are the cert and key file supposed to be created at the same time?

    php artisan websockets:serve always works ("Starting the WebSocket server on port 6003..."), no matter the config and even misspelled cert file paths. Is there a way to get some feedback in the console if the SSL settings / cert works as expected or not? I've tried --debug, but no difference.

    I'm using the Pusher settings with Echo and with port 6003. Getting this error in the browser: WebSocket connection to 'wss://removed-domain.com:6003/app/6c8c855975c5f6c4ad88?protocol=7&client=js&version=4.3.1&flash=false' failed: WebSocket is closed before the connection is established.

    If I stop the websockets server, I get connection refused error. So it seems it's trying to connect to the websockets server correctly.

    I think I've tried all the suggested server and client settings, from the SSL related issues here.

    I'm suspecting something is wrong with my cert (although it works fine for HTTPS with Apache), but I don't know how to investigate further. I'm stuck.

    Does anyone have some clues?

    Reviewed by eminos at 2019-01-17 11:49
  • 11. pusher-js did not reconnect after the 2nd offline situation ...

    First i will thank you very much for this Product. Wow!

    We have a major Problem with our "little" websocket setup. Each time, (or better to say, after the 2nd Energy-Saver time of my Mobile Phone , my vue.js web-app failed to receive websocket events.

    Our old Setup .. with the node.js based laravel-websocket-service / socket-io transport inside the frontend client was working over a year without this effect. So i started to investigate:

    • The laravel-echo javascript library is unchangend .. so there is not the problem.
    • The major change is the pusher-js bridge (instead of the socket-io).

    TLdr .. the pusher-js (version 4.4.x) is only reconnection 1 times on your laravel-websocket server after a (short) offline situation. This is also testable with firefox-dev there is a "offline-switch" ..

    After the first "breakdown" it reconnects very fine ... your server is opening a new connection .. and voila ..

    After the next offline-breakdown , the pusher-js is not re-connecting by websocket (ws or wss) it is preffering a xhr-streaming connection .. (this can be forbidden by:

    disabledTransports: ['sockjs', 'xhr_polling', 'xhr_streaming'],

    but .. if those transports are disabled .. it stops with re-connecting ..

    I tested many variants of pusher-js connection params .. lastly ending with this list of "rules" ..

    encrypted: true, wsHost: process.env.ECHO_SERVER_PUSHER, wssHost: process.env.ECHO_SERVER_PUSHER, httpHost: process.env.ECHO_SERVER_PUSHER, forceTLS: true, httpPort: 443, httpsPort: 443, wsPort: 443, wssPort: 443, // enabledTransports: ['ws', 'wss'], disabledTransports: ['sockjs', 'xhr_polling', 'xhr_streaming'], disableStats: true

    but .. the pusher-js has his own rules (maybe .. because .. your product .. is tooo good ;-) ) ..

    So .. if you want to be "pusher-js" free (it makes also sense, because you are digging with your product against their product) .. maybe you should take a look onto socket-io .. or ..

    Or implement a xhr-streaming fallback possibility ..

    With pusher-js directly on pusher.com it works without any problems, because they have the fallback transport mechanism .. so there is no breakdown ..

    But with this limitation, its a showstopper ..

    Reviewed by ibrainventures at 2019-04-28 23:27
  • 12. Problem with config wss, certs, etc

    First of all, many thanks to the team for making this package possible. I will detail the exact steps I take to try to configure the wss.

    My configuration

    - Laravel 5.7
    - beyondcode/laravel-websockets 1.3.0
    - pusher/pusher-php-server 4.1.5
    
    

    Nginx with proxy reverse

    location /app {
            proxy_pass             http://127.0.0.1:6001;
            proxy_read_timeout     60;
            proxy_connect_timeout  60;
            proxy_redirect         off;
    
            # Allow the use of websockets
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    

    STEP

    1. I have created a domain without https.
    2. Config websockets.php and broadcasting.php (simple config)
    3. I have uploaded the project and it works without problem, I can enter the panel and see the statistics.
    4. Seeing that everything works perfectly.

    NOW, ACTIVATE WSS

    STEP I should mention that I have read and tested many tutorials and issues here.

    1. I have created some certificates on my server with this command. sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/websockets-selfsigned.key -out /etc/ssl/certs/websockets-selfsigned.crt
    2. Open file config/websockets.php and the configuration
    ....
    ....
    'apps' => [
            [
                'id' => env('PUSHER_APP_ID'),
                'name' => env('APP_NAME'),
                'key' => env('PUSHER_APP_KEY'),
                'secret' => env('PUSHER_APP_SECRET'),
                'enable_client_messages' => true,
                'enable_statistics' => true,
            ],
        ],
    ....
    ....
    
    'ssl' => [
            /*
             * Path to local certificate file on filesystem. It must be a PEM encoded file which
             * contains your certificate and private key. It can optionally contain the
             * certificate chain of issuers. The private key also may be contained
             * in a separate file specified by local_pk.
             */
            'local_cert' => env('LOCAL_CERT', null),
    
            /*
             * Path to local private key file on filesystem in case of separate files for
             * certificate (local_cert) and private key.
             */
            'local_pk' => env('LOCAL_KEY', null),
    
            /*
             * Passphrase with which your local_cert file was encoded.
             */
            'passphrase' => null,
            'verify_peer' => false,
            'allow_self_signed' => true,
        ],
    
    

    My .ENV

    PUSHER_APP_ID=666666
    PUSHER_APP_KEY='AAbLk31NuAA'
    PUSHER_APP_SECRET='VV6dfnj6K32aCNuFa'
    PUSHER_APP_CLUSTER=mt1
    PUSHER_SCHEME='https'
    
    LOCAL_CERT='/etc/ssl/certs/websockets-selfsigned.crt'
    LOCAL_KEY='/etc/ssl/private/websockets-selfsigned.key'
    LOCAL_PEM='/etc/ssl/certs/websockets-selfsigned.pem'
    
    MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
    MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
    
    1. Open file config/brodcasting.php and the configuration
    'pusher' => [
                'driver' => 'pusher',
                'key' => env('PUSHER_APP_KEY'),
                'secret' => env('PUSHER_APP_SECRET'),
                'app_id' => env('PUSHER_APP_ID'),
                'options' => [
                    'cluster' => env('PUSHER_APP_CLUSTER'),
                    'encrypted' => true,
                    'useTLS' => true,
                    'host' => '127.0.0.1',
                    'port' => 6001,
                    'scheme' => env('PUSHER_SCHEME'),
                    'curl_options' => [
                        CURLOPT_SSL_VERIFYHOST => 0,
                        CURLOPT_SSL_VERIFYPEER => 0,
                    ],
                ],
            ],
    
    1. Add config for nginx.ssl.conf (Port 443)
    location /app {
            proxy_pass             https://127.0.0.1:6001;        
            proxy_read_timeout     60;
            proxy_connect_timeout  60;
            proxy_redirect         off;
    
            # Allow the use of websockets
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    
    1. Restart nginx
    2. Now Testing laravel-websockets panel and fail.

    WebSocket connection to 'wss://websockets.ubublog.com:80/app/ygbLk87NuyN?protocol=7&client=js&version=4.3.1&flash=false' failed:

    image


    I have followed all the steps as per various tutorials and reviews here and I get this error. If anyone has managed to get wss working, can you tell me where I am going wrong. The steps are simple but there is something wrong with setting it up.

    Reviewed by ssheduardo at 2022-05-18 11:52
  • 13. Connection failed in AWS EC2

    I'm using laravel-websockets and is working like a charm in my local docker machine but I can't seem to make it work when I deploy it in the AWS EC2 machine.

    This is the error message I get:

    pusher.min.js:8 WebSocket connection to 'wss://sample.project:6001/app/b0901feacd04936e?protocol=7&client=js&version=4.3.1&flash=false' failed:

    These are my config files:

    broadcasting.php

            'pusher' => [
                'driver' => 'pusher',
                'key' => env('PUSHER_APP_KEY'),
                'secret' => env('PUSHER_APP_SECRET'),
                'app_id' => env('PUSHER_APP_ID'),
                'options' => [
                    'cluster' => env('PUSHER_APP_CLUSTER'),
                    'host' => '127.0.0.1',
                    'port' => 6001,
                    'scheme' => 'http',
                ],
            ],
    

    websockets.php

      'apps' => [
           [
               'id' => env('PUSHER_APP_ID'),
               'name' => env('APP_NAME'),
               'key' => env('PUSHER_APP_KEY'),
               'secret' => env('PUSHER_APP_SECRET'),
               'enable_client_messages' => false,
               'enable_statistics' => true,
           ],
       ],
    

    bootstrap.js

    window.Echo = new Echo({
        broadcaster: 'pusher',
        key: process.env.MIX_PUSHER_APP_KEY,
        cluster: process.env.MIX_PUSHER_APP_CLUSTER,
        wsHost: window.location.hostname,
        wsPort: 6001,
        forceTLS: false,
        disableStats: true,
    });
    

    I've also opened 6001 port in my security group.

    But I can't make it work. I've tried a lot of the fixes in SO questions but none worked, am I missing something? In desperate need of help here.

    Thank you very much.

    Reviewed by hfmiguel-baufest at 2022-05-11 17:13
  • 14. Get user data in websocket handlers

    This is my onClose function code in WebSocketHandler.php file:

     public function onClose(ConnectionInterface $connection)
        {
    
            $allChannels = $this->channelManager->getChannels($connection->app->id);
    
            foreach ($allChannels as $channelData) {
                $data = $channelData;
            }
            dd($data);
    
            $this->channelManager->removeFromAllChannels($connection);
    
            DashboardLogger::disconnection($connection);
    
            StatisticsLogger::disconnection($connection);
        }
    
    

    and when the user closes the tab or browser my onClose function gives me $data in console logging which is this response:

    BeyondCode\LaravelWebSockets\WebSockets\Channels\PresenceChannel {#719
      #users: array:1 [
        1 => array:9 [
          "id" => 1
          "email" => "[email protected]"
          "username" => "BlackHill"
          "type" => 0
          "steam_id" => "76561198107211703"
          "stay_login" => 0
          "email_verified_at" => null
          "created_at" => "2022-03-21T22:54:53.000000Z"
          "updated_at" => "2022-04-23T20:13:19.000000Z"
        ]
      ]
      #sockets: array:1 [
        "161595151.817952840" => "1"
      ]
      #channelName: "presence-users"
    }
    

    I need to access #users array to apply changes to any user who leaves. In this issue they managed to get channelName but I did not get #users using their solution!

    Reviewed by S1ipKn0T at 2022-05-11 11:17
  • 15. Not able to connect websocket with Ubuntu + Apache Server

    We have followed the instructions and installed it locally. It was working fine with our local host. We have moved a temporary development server (digital ocean - for test purposes with a mobile application as a client) and stopped working.

    Server Configuration : Digital Ocean Droplet + Ubutu + Apache 2 + PHP

    I have whitelisted the port from the Digital Ocean and the server firewall (allowed the port). I have configured the supervisor and the 6001 port is RUNNING. Checked via (netstat -tulpn | grep 6001)

    I have put the application in a folder http://xx.xx.xx.xx/laravel/public/ and am able to access debug dashboard via http://xx.xx.xx.xx/laravel/public/laravel-websockets

    ISSUE I am not able to connect with WebSocket and getting the below error with debug dashboard.

    WebSocket connection to 'ws://xx.xx.xx.xx:6001/app/local?protocol=7&client=js&version=4.3.1&flash=false' failed:

    Question 1: Will I have configured SSL for this? We are in development and want to integrate for testing purposes. Question 2 Can someone help with Apache Proxy Reverse or Condition? Will I have to write those?

    Please help me. Thanks in advance.

    Reviewed by codoffer at 2022-05-10 17:02
  • 16. hello

    WebSocket connection to wss://e6adcbdb.alx-cod.online:8003/ws/fbceb554d83f72cad04ce98e811b9fb61ce3570ac039fe2dce9e0aeb245711b8 failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED. Agent down.

    Reviewed by yirga1 at 2022-05-10 11:27
  • 17. validate_channels(): Argument #1 ($channels) must be of type array, Collection given

    Everything was working fine for a long time until now. I started to get this error out of nowhere: Pusher\\Pusher::validate_channels(): Argument #1 ($channels) must be of type array, Illuminate\\Support\\Collection given, called in /vendor/pusher/pusher-php-server/src/Pusher.php on line 341

    The error occurs when trying to broadcast an event like so: broadcast(new UpdateListEvent());

    Using Laravel 9 and laravel-webscokets 1.13.1

    Any ideas?


    Update 1: Figured out that it was a particular composer update that caused this issue and the update was to the main Laravel package: laravel/framework (9.x-dev 3be7023 => 9.x-dev c51ef98) After update to 9.x-dev c51ef98 it stops working. I think the issue is with Laravel it self and not laravel-websockets

    Reviewed by butaminas at 2022-05-09 13:00
Websockets-Client (Sample) laravel

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Mar 8, 2022
Master Websockets Laravel

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Mar 8, 2022
Get estimated read time of an article. Similar to medium.com's "x min read". Multilingual including right-to-left written languages. Supports JSON, Array and String output.

Read Time Calculates the read time of an article. Output string e.g: x min read or 5 minutes read. Features Multilingual translations support. Static

Sep 7, 2021
A package for Laravel One Time Password (OTP) generator and validation without Eloquent Model, since it done by Cache.

Laravel OTP Introduction A package for Laravel One Time Password (OTP) generator and validation without Eloquent Model, since it done by Cache. The ca

May 7, 2022
List of 77 languages for Laravel Framework 4, 5, 6, 7 and 8, Laravel Jetstream , Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova and Laravel Spark.

Laravel Lang In this repository, you can find the lang files for the Laravel Framework 4/5/6/7/8, Laravel Jetstream , Laravel Fortify, Laravel Cashier

May 24, 2022
⚡ Laravel Charts — Build charts using laravel. The laravel adapter for Chartisan.
⚡ Laravel Charts — Build charts using laravel. The laravel adapter for Chartisan.

What is laravel charts? Charts is a Laravel library used to create Charts using Chartisan. Chartisan does already have a PHP adapter. However, this li

May 19, 2022
Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster.

Laravel Kickstart What is Laravel Kickstart? Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster. It com

Jan 8, 2022
Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app
Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Apr 20, 2022
Laravel Segment is an opinionated, approach to integrating Segment into your Laravel application.

Laravel Segment Laravel Segment is an opinionated, approach to integrating Segment into your Laravel application. Installation You can install the pac

May 16, 2022
Laravel Sanctum support for Laravel Lighthouse
Laravel Sanctum support for Laravel Lighthouse

Lighthouse Sanctum Add Laravel Sanctum support to Lighthouse Requirements Installation Usage Login Logout Register Email Verification Forgot Password

May 27, 2022
Bring Laravel 8's cursor pagination to Laravel 6, 7

Laravel Cursor Paginate for laravel 6,7 Installation You can install the package via composer: composer require vanthao03596/laravel-cursor-paginate U

Jan 13, 2022
A package that uses blade templates to control how markdown is converted to HTML inside Laravel, as well as providing support for markdown files to Laravel views.
A package that uses blade templates to control how markdown is converted to HTML inside Laravel, as well as providing support for markdown files to Laravel views.

Install Install via composer. $ composer require olliecodes/laravel-etched-blade Once installed you'll want to publish the config. $ php artisan vendo

Jul 5, 2021
A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic

A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic! concepts like , Hijri Dates & Arabic strings and so on ..

May 15, 2022
Jetstrap is a lightweight laravel 8 package that focuses on the VIEW side of Jetstream / Breeze package installed in your Laravel application

A Laravel 8 package to easily switch TailwindCSS resources generated by Laravel Jetstream and Breeze to Bootstrap 4.

May 13, 2022
Laravel Jetstream is a beautifully designed application scaffolding for Laravel.

Laravel Jetstream is a beautifully designed application scaffolding for Laravel. Jetstream provides the perfect starting point for your next Laravel application and includes login, registration, email verification, two-factor authentication, session management, API support via Laravel Sanctum, and optional team management.

May 18, 2022
Laravel Larex lets you translate your whole Laravel application from a single CSV file.
Laravel Larex lets you translate your whole Laravel application from a single CSV file.

Laravel Larex Translate Laravel Apps from a CSV File Laravel Larex lets you translate your whole Laravel application from a single CSV file. You can i

Apr 2, 2022
A Laravel package that adds a simple image functionality to any Laravel model
A Laravel package that adds a simple image functionality to any Laravel model

Laraimage A Laravel package that adds a simple image functionality to any Laravel model Introduction Laraimage served four use cases when using images

Feb 3, 2022
A Laravel extension for using a laravel application on a multi domain setting
A Laravel extension for using a laravel application on a multi domain setting

Laravel Multi Domain An extension for using Laravel in a multi domain setting Description This package allows a single Laravel installation to work wi

May 17, 2022
Example of using abrouter/abrouter-laravel-bridge in Laravel
Example of using abrouter/abrouter-laravel-bridge in Laravel

ABRouter Laravel Example It's a example of using (ABRouter Laravel Client)[https://github.com/abrouter/abrouter-laravel-bridge] Set up locally First o

Oct 14, 2021