Coder Social home page Coder Social logo

beyondcode / laravel-websockets Goto Github PK

View Code? Open in Web Editor NEW
5.1K 68.0 595.0 1.13 MB

Websockets for Laravel. Done right.

Home Page: https://beyondco.de/docs/laravel-websockets

License: MIT License

PHP 93.70% Blade 6.30%
laravel websockets pusher laravel-echo hacktoberfest

laravel-websockets's Introduction

Laravel WebSockets 🛰

Note

Laravel WebSockets is no longer maintained. If you are looking for a PHP-based WebSocket solution, check out Laravel Reverb which is also built on top of ReactPHP and allows you to horizontally scale the WebSocket server.

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://tinkerwell.app/?ref=github

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.

laravel-websockets's People

Contributors

anthonyvancauwenberghe avatar bytestream avatar chapeupreto avatar crynobone avatar erikn69 avatar erlangparasu avatar francislavoie avatar freekmurze avatar irazasyed avatar juandmegon avatar kloining avatar koozza avatar lionslair avatar lkaemmerling avatar lukepolo avatar mahansky avatar mattiasgeniar avatar mdprotacio avatar mpociot avatar nunomaduro avatar olssonm avatar rennokki avatar ricardo-lobo avatar rinordreshaj avatar robindrost avatar simonbuehler avatar snellingio avatar stayallive avatar ttomdewit avatar vikas5914 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-websockets's Issues

Horizontal scalability

I'm just opening up this issue because this is something I've had to implement myself in my own Ratchet Websocket server implementation.

I see that you're using ChannelManager to persist connection state. This is fine for most situations, but I suggest thinking about the flexibility of it early on because I'm sure some users will hit walls with limits on vertical scaling of their WS server.

This is how I did it:

  • Require clue/redis-react to have an async Redis client
  • Use Redis as the broadcast driver instead
  • Open two Redis connections on the WS server. One for subscribing, and one for publishing. (This is because of the way Redis works, a connection which subscribes to things cannot publish or run any commands other than subscription related ones and receiving messages... so a second connection is needed to allow publishing events from the WS instance)
  • Whenever a connection comes in, subscribe to Redis on a channel like connections:$connId or whatever. This is to allow other WS server instances to trigger actions on a connection they don't own themselves. e.g. connection limit per user, so it triggers an event to kill off the oldest connection by its ID.
  • Whenever a connection subscribes to a channel, also subscribe on Redis on behalf of the connection. This way you receive Laravel Broadcasting messages via Redis.
  • Whenever a connection publishes a message, also publish to Redis to propagate to other WS instances.
  • When a connection disconnects, unsubscribe from Redis for all the channels it was listening to, but only if it's the last locally-known connection to subscribe to that channel. Also publish a message on the connections:$connId channel to tell any other instances that this one's disconnecting... then unsubscribe from that channel as well.
  • etc. (I'm sure I missed something...)

Here's a bunch of implementation details on how I did it (no full source because it was for a closed-source project) simonhamp/laravel-echo-ratchet-server#2

Obviously this would lose some compatibility with the Pusher server-side stuff due to using Redis as the broadcast driver, but all the client-side Pusher stuff should still work as-is, I think. Just need to load balance your websocket server instances (your docs mention HAProxy or Nginx to proxy, Caddy works just fine as well)

Edit: I just realized you don't necessarily need to switch to Redis for broadcasting. TriggerEventController could just publish to Redis itself. Pusher compatibility would be kept that way. You could just send those events to any of the echo server instances and they can propagate it out.

Realtime Statistics not showing

I have followed the installation instructions step by step and have laravel-websockets working as expected - notifications are sent and received. I have also configured SSL support and this is also working. I am running the latest version of laravel-websockets 1.0.2.

When I view the Debug Dashboard I can see the Events at the bottom of the screen and these update in real time - I do not however see any statistics in the graph section at the top.

Do I need to do anything else to make this work? I can see the database table websockets_statistics_entries but it is empty, I tried sending lots of messages one after another but still do not get any data.

Dashboard additional features

As a feature request, it would be amazing to be able to have the debug dashboard in Telescope under a Websocket section instead of yet another hidden login page.

In addition, it would be nice to be able to drill down into the events to see data that was passed, who sent it, and which clients are currently connected etc.

StatisticsUpdated job crashing

I've gone through the install and things seem to be working great as a drop-in replacement for Pusher - thanks! This is way nicer to use than the node echo server! :-)

I do keep seing a failed job in the horizon queue runner though - and no stats are being gathered (but the notifications are coming through ok in the app). The queue runner is outputting :

[2018-12-05 09:15:50][199] Processing: BeyondCode\LaravelWebsockets\Statistics\Events\StatisticsUpdated

   Symfony\Component\Debug\Exception\FatalErrorException  : method_exists(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "BeyondCode\LaravelWebsockets\Statistics\Events\StatisticsUpdated" of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide an autoloader to load the class definition

  at /Users/ohffs/Documents/code/examdb/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastEvent.php:43
    39|      * @return void
    40|      */
    41|     public function handle(Broadcaster $broadcaster)
    42|     {
  > 43|         $name = method_exists($this->event, 'broadcastAs')
    44|                 ? $this->event->broadcastAs() : get_class($this->event);
    45|
    46|         $broadcaster->broadcast(
    47|             Arr::wrap($this->event->broadcastOn()), $name,


   Whoops\Exception\ErrorException  : method_exists(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "BeyondCode\LaravelWebsockets\Statistics\Events\StatisticsUpdated" of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide an autoloader to load the class definition

  at /Users/ohffs/Documents/code/examdb/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastEvent.php:43
    39|      * @return void
    40|      */
    41|     public function handle(Broadcaster $broadcaster)
    42|     {
  > 43|         $name = method_exists($this->event, 'broadcastAs')
    44|                 ? $this->event->broadcastAs() : get_class($this->event);
    45|
    46|         $broadcaster->broadcast(
    47|             Arr::wrap($this->event->broadcastOn()), $name,

PHP Fatal error:  method_exists(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "BeyondCode\LaravelWebsockets\Statistics\Events\StatisticsUpdated" of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide an autoloader to load the class definition in /Users/ohffs/Documents/code/examdb/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastEvent.php on line 43

I'm using redis as the queue driver. I've tried the usual dump-autoload etc, restarting everything - but it keeps happening. I had a look at the StatisticsUpdated class and nothing was leaping out at me as being the 'ah-ha!' problem - sorry :-/

difficulties getting multi-tenancy to work

Ok so I'm trying to decouple the demo repository into two installations. And I'll also be using the "server-only" installation to work with all my other projects that currently use Pusher.

So I created a new mysql database 'db_socketmaster' and set it inside .env

laravel new socketmaster
cd socketmaster
composer require beyondcode/laravel-websockets
composer require pusher/pusher-php-server "~3.0" (as per instructions but seems redundant since this is a dependency of beyondcode/laravel-websockets)
pa key:generate
pa migrate
pa vendor:publish (to publish the config and migrations from websockets)

I'm running this off Valet with --secure

In my websockets.php. I added the necessary entries to the SSL part as per the new Valet configuration.. no problem there

Then in the apps section I added this

    'apps' => [
        [
            'id' => '4036967643',
            'name' => 'site-1',
            'key' => 'E2fAKqHM0EvOAL',
            'secret' => 'InMBQzUtRueKdf',
            'enable_client_messages' => false,
            'enable_statistics' => true,
        ],
        [
            'id' => '6641070849',
            'name' => 'site-2',
            'key' => '7kWyUamVkIaAZw',
            'secret' => 'iLKvyU3f3ftzJK',
            'enable_client_messages' => false,
            'enable_statistics' => true,
        ],
        [
            'id' => '9566892751',
            'name' => 'site-3',
            'key' => 'zRr6ThwvOPoIeK',
            'secret' => 'HufIJdYCfWDGBh',
            'enable_client_messages' => false,
            'enable_statistics' => true,
        ],
        [
            'id' => '2856995658',
            'name' => 'websockets-demo',
            'key' => 'gzfYlnfja2LiS4',
            'secret' => '1jHb1sxlhavkS8',
            'enable_client_messages' => false,
            'enable_statistics' => true,
        ],
        // [
        //     'id' => '',
        //     'name' => '',
        //     'key' => '',
        //     'secret' => '',
        //     'enable_client_messages' => false,
        //     'enable_statistics' => true,
        // ],
    ],

Ignore the first 3, so the 4th one is for the laravel-websockets-demo. I used a random generator to generate all the fake app IDs and key/secrets

I set the broadcast driver to pusher (or in my case pusher-dev)

And then inside broadcasting.php config file, this is where I'm confused

I put this

        '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',
            ],
        ],

        'pusher-dev' => [
            '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',
                'curl_options' => [
                    CURLOPT_SSL_VERIFYHOST => 0,
                    CURLOPT_SSL_VERIFYPEER => 0,
                ],
            ],
        ],  

I set another connection "pusher-dev" because on production I don't want to disable the host verification. I set the scheme to https for both.. and where I'm confused is.. what am I supposed to put for the key/secret/app_id ? since this is not for any particular app but is managing multiple apps

So I just commented out those values. Also I think the cluster is redundant at this point am I right?

I ran php artisan websockets:serve, no errors here

Then I modified the bootstrap.js inside the demo to this:

window.Echo = new Echo({
    broadcaster: 'pusher',
    // key: process.env.MIX_PUSHER_APP_KEY,
    // wsHost: window.location.hostname,
    key: 'gzfYlnfja2LiS4',
    wsHost: 'socketmaster.dev',
    wsPort: 6001,
    wssPort: 6001,
    disableStats: true,
});

I'm using the "key" from the 4th app, the 'websocket-demo' app. And for the host I'm using my "socket manager" url, which is correct. I'm able to visit the debug dashboard at https://socketmaster.dev/laravel-websockets

I ran npm run prod

And then I visited the chat demo, logged in. I get no errors in the console or the network tab. But in my terminal running the websockets I get an 'Invalid Signature' error

New connection opened for app key gzfYlnfja2LiS4.
Connection id 125098324.201156164 sending message {"event":"pusher:connection_established","data":"{\"socket_id\":\"125098324.201156164\",\"activity_timeout\":30}"}
2856995658: connection id 125098324.201156164 received message: {"event":"pusher:subscribe","data":{"auth":"websocketkey:34efbef0371bee17728389eb9b08f4dd53077ee2cccaadfe90f7a0637db67a34","channel_data":"{\"user_id\":1,\"user_info\":{\"id\":1,\"name\":\"Charlie\",\"email\":\"[email protected]\",\"email_verified_at\":null,\"created_at\":\"2018-12-05 02:10:01\",\"updated_at\":\"2018-12-05 02:10:01\"}}","channel":"presence-chat"}}.
Exception `BeyondCode\LaravelWebSockets\WebSockets\Exceptions\InvalidSignature` thrown: `Invalid Signature`
2856995658: exception `BeyondCode\LaravelWebSockets\WebSockets\Exceptions\InvalidSignature` thrown: `Invalid Signature`.
Connection id 125098324.201156164 sending message {"event":"pusher:error","data":{"message":"Invalid Signature","code":4009}}
2856995658: connection id 943809179.970880291 received message: {"event":"pusher:ping","data":{}}.
Connection id 943809179.970880291 sending message {"event":"pusher:pong"}

I also gets CORS errors afterwards

Is this purely a CORS issue?

My 'allowed_origins' array is left empty on socketmaster's websockets.php configuration

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.`

Dashboard not working when server under other URL

I have the following setup:
Webserver 1 : dev.myapp.com
Socketserver 1 : ws-dev.myapp.com

When i now try to connect to the Sockerserver from the dashboard it tries to connect to dev.myapp.com instead of ws-dev.myapp.com. Looks like it doesn't now that is should connect to ws-dev.myapp.com, because it is not specified :) An App Option for specifying the URL would be good.

I'll submit a pr shortly :)

Pusher API ? How to query channels / users in channels ?

In my current video chat app, as part of the admin dashboard, it's possible to query the rest api which in turn queries Pusher to ask how many users are in which channels without having to actually join the channels on the client side.. like this:

    public function channelStats(Request $request)
    {
        $users = User::get(['id', 'name', 'gender'])->keyBy('id');

        $usersInOnline = Pusher::get('/channels/presence-online/users');
        $usersInLobby = Pusher::get('/channels/presence-lobby/users');
        $usersInVideo = Pusher::get('/channels/presence-video/users');

        $onlineUserIds = collect($usersInOnline['result']['users'])->map(function ($user) { return $user['id']; });
        $lobbyUserIds = collect($usersInLobby['result']['users'])->map(function ($user) { return $user['id']; });
        $videoUserIds = collect($usersInVideo['result']['users'])->map(function ($user) { return $user['id']; });

        return [
            'online' => count($usersInOnline['result']['users']),
            'lobby' => count($usersInLobby['result']['users']),
            'video' => count($usersInVideo['result']['users']),
            'users' => [
                'online' => $users->whereIn('id', $onlineUserIds),
                'lobby' => $users->whereIn('id', $lobbyUserIds),
                'video' => $users->whereIn('id', $videoUserIds),
            ],
        ];
    }

My question is.. how could I achieve this with laravel-websockets ?

Unable to push events from the server using authorization

Good time of the day!
Recently, i've been using laravel-echo-server to with realtime notifications and events, but i've decided to switch to laravel-websockets due to the fact, that it is one less external dependency for the project.

While i was using laravel-echo-server, i had no problem receiving and sending events, however, when i switch to this package, i'm no longer able to send some of the events from the server to the client.

Any triggered event (checked with app('log')->info($event)) wont be visible in the console, nor in the dashboard.

Here is the gist with current configuration.
Gist with current configuration

Whenever server is trying to trigger the event, Laravel errors with Unknown auth_key. But this is only happening on the events triggered by the /laravel-websockets dashboard, other events, except for the presence channels are simply ignored.

Presence channel works just fine, no problem there, i'm able to display number of active users in the real time, but when i try to push event on the other channels, they simply wont go through.

Any help on this issue?

Any plans on using native PHP websocket?

Currently we have this package that mostly supports websockets https://github.com/walkor/phpsocket.io and also https://reactphp.org/

Do you guys have plans on integrating this kind of connection? Is this package only wraps the existing implemented pusher in laravel services and just added with Dashboard to manage it?

Edit:
I have seen you guys have this WebSocketHandler.php that you used Ratchet, however I don't know why it is bound to Pusher only (correct me if I am wrong)

It would be better to make this class to have a default connection which is the pusher, then later if someone would like to add more connections or different implementations that could follow the contracts, that helps a lot.

This could join other developers specially who's more knowledgeable with the above links I mentioned.

Is it possible to stream video to subscribers from Laravel

Greetings,

I'm working on a mobile app, I'm thinking to use this package for realtime communication.

I'm wondering if it's possible to stream a video file from laravel to all the connected clients using this package?

Thanks for any help. 🥂

Not working with Laravel Valet

Thank you for making this package. It comes at the perfect time for me, I'm just starting to use websockets on a project I've got running.

It might be an oversight on my part, but I can't get this to work with Laravel Valet. Using Pusher with Laravel's default config works, but as soon as I make the necessary changes in the config and try to broadcast an event I get an empty Illuminate\Broadcasting\BroadcastException.

config/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' => 'https',
                'curl_options' => [
                    CURLOPT_SSL_VERIFYHOST => 0,
                    CURLOPT_SSL_VERIFYPEER => 0,
                ]
            ],
        ],

config/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,
        ],
    ],

    'app_provider' => BeyondCode\LaravelWebSockets\Apps\ConfigAppProvider::class,

    'allowed_origins' => [
        //
    ],

    'max_request_size_in_kb' => 250,

    'path' => 'laravel-websockets',

    'statistics' => [
        'model' => \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry::class,

        'interval_in_seconds' => 60,

        'delete_statistics_older_than_days' => 60,
    ],

    'ssl' => [
        'local_cert' => '/Users/ronflorax/.config/valet/Certificates/snookerscores.test.crt',

        'local_pk' => '/Users/ronflorax/.config/valet/Certificates/snookerscores.test.key',

        'passphrase' => null,

        'verify_peer' => false,
    ],

Forced use of Facades

Hi,

this library enforces the use of Facades. Facades are optional and userland helpers that don't belong in a Laravel or Lumen framework library.

I'm currently testing the changes required to achieve this, so far it seems pretty straightforward ;-)
I'll create a PR from my fork.

Thanks again for this great package!

Installation with Lumen

I'll try to figure out how to install and use laravel-websockets with Lumen and come back here when I have a working setup.

Tips and hints appreciated! :)

Zero Downtime Deployment

So what would be the best way to deploy this using a zero downtime deployment system (such as Deployer, Laravel Envoy, etc.)? The problem would be that you will be running a version of the websockets server using an older version of your site. So say it would be running release 3 when the current site is on release 4. So it will never pick up any changes to your configuration file for example.

Laravel Horizon has the same problem, but it has a terminate console command. So part of your deployment, you just terminate the current running Horizon and supervisord in the background will restart it back up. But it will restart it in the latest release.

Is there any way to terminate the currently running websockets server short of logging into the server and killing the current running process for the server? Thanks.

run daemon on windows

Hello documentation only describes run daemon on Linux, How can do it on windows? Thank you

Connection count is not accurate after reset

The current implementation of ChannelManager::getConnectionCount in ArrayChannelManager counts the active connections per channel. In my opinion this does not show the real connection count.

For example:

  • a client may not connect to any channel which is calculated as 0 connection
  • a client may connect to n channel which is calculated as n connections

Maybe it is not relevant, but Pusher connections counted per WebSocket connections not per channel connections. This information can be found in their FAQ: https://support.pusher.com/hc/en-us/articles/202092346-How-are-connections-counted-

A connection is counted as a WebSocket connection to Pusher.

Events are not being broadcasted unless I open Dashboard

Took me a while to figure it out. It was, at first, looking like it was not working at all. I had just installed it and configured like I use to do with Pusher, then added the proper ports and so, but nothing was hitting the terminal log, so I finally opened the dashboard, then magically events started to show up on the terminal and the front end.

So I disconnected the dashboard, closed the page and created and, after a while, created a new event, which again was not showing up on terminal, so I opened the dashboard and voilá! there was it, working.

Then I moved to my home machine, git pull, composer install, migrate, npm run watch, opened the interface, it connected successfully to the server, but not a single event is showing in terminal log, all I get is ping and pongs.

Do I still need a pusher key?

I can see in the example code provided in your documentation you have used something similar a lot:

'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' => 'http'
    ],
],

and:

import Echo from "laravel-echo"

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-key',
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true,
});

So do I still need a PUSHER_APP_SECRET or PUSHER_APP_ID or PUSHER_APP_CLUSTER or pusher-key for this to work?!

Do you plan to support Laravel 5.5

I am running Laravel 5.5 and get following error when installing the package:

beyondcode/laravel-websockets 1.0.0 requires illuminate/routing 5.7.* -> satisfiable by illuminate/routing[v5.7.0, v5.7.1, v5.7.10, v5.7.11, v5.7.15, v5.7.2, v5.7.3, v5.7.4, v5.7.5, v5.7.6, v5.7.7, v5.7.8, v5.7.9].

Do you plan to support Laravel 5.5. in future?

Thx, Johnson

Laravel Echo will still connect to Pusher as fallback

When connection fails, it will still try and connect to Pusher (over XHR) as a fallback.

More specifically to http://sockjs.pusher.com/pusher/app/.... Did I forget to change something in my config/echo/etc. files or is this expected behavior for now?

Safari not using specified wsHost

I am trying to override the Echo.options.wsHost, but Safari is still using the Pusher host. I am using it like specified in the docs: wsHost: 'xxx.test',. It is working in Chrome on desktop, but not Chrome on iOS, nor Safari.

The Echo instance is globally available, and when typing Echo.options.wsHost it does return xxx.test.

Here is the feed of the socket:
Feed

Why is the wsHost not recognized by Safari?

global binary / phar

Awesome work :) If I understand correctly, laravel-websockets can run fully independent of the actual project, so would it make sense to release a stand-alone version? Because you have multi-tenancy I feel it makes more sense to decouple it from my actual application (eg. 1 pusher server, serving test/staging/production environments or multiple small apps (looking at the impressive stats on the docs :))

The only thing you would need is the database? Perhaps similiar to laravel-socket-server, just use 1 (global?) binary .phar file, 1 config file and optionally 1 sqlite file. Would make it easy to setup/deploy it as stand-alone app.

Connection Refused when using Python websocket client

Hi, thanks for this awesome package.
I've tried to connect to the websocket server using Python client this and the code I've used is this:

import websocket
ws = websocket.WebSocket()
ws.connect("ws://localhost", http_proxy_host="::", http_proxy_port=6001)

I just want to connect and see if the connection was successful or not via the dashboard provided by this package. However, the error I've got is:

socket.error: [Errno 61] Connection refused

Are there any other settings I've to add in order to establish the connection?

Unable to register custom WebSocket Handler

Hi,
First of, thanks for your great work!

When registrering the route for a custom WebSocket handler using:
WebSocketsRouter::webSocket('/socket', \App\WS\Handlers\Handler::class)
in reoutes/web.php laravel is unable to boot with the following exception:
Target [Symfony\Component\Console\Output\OutputInterface] is not instantiable while building [BeyondCode\LaravelWebSockets\Server\Logger\WebsocketsLogger].

My workaround for the issue is to call:

use Symfony\Component\Console\Output\NullOutput;
app()->singleton(WebsocketsLogger::class, function () {
    return (new WebsocketsLogger(new NullOutput()))->enable(false);
});

before the route registering. I guess that defering the route registering to after the the server has setup the loggers would be a solution?

Questions - 100% Pusher replacement , channels and SPA client

Hi,

First of all thanks for another great package and another great contribution for the community !!

Im thinking about replacing our existing pusher implemention by this package, my idea is a standalone project just for this , and i mean just to serve websockets.

I had a quick look on the documentation, i think i didn't miss anything, so and i have some questions:

Sorry if the answers are in the docs, i think not.

  • can i completly replace pusher ?
  • its possible to have private and public channels ?
  • How can we integrate laravel-websockets in a SPA (vuejs) app ? Laravel echo ? I just need the technical info, bc if possible and no right package we can build a js package.

Thanks
CV

laravel echo not reconnect after fail

laravel echo not reconnect after fail
here is my code
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
wsHost: window.location.hostname,
wsPort: 6001,
disableStats: true,
});

How to use this in an api with 2 separated repositories?

Hi,

What does it change if we use this package in a situation with Laravel as backend and React as frontend, in two separated repositories?

I suppose that we don't have to configure Laravel Echo in bootstrap.js, which extra steps we have to do?
Will it work anyway?

Thanks in advance!

Problem Connecting Debug Dashboard to Websocket Server

Hey I followed your guide/docs for installation and setup.
I run the php artisan websockets:serve command, travel to the debug dashboard url, select my app and click on connect.
I then receive the following error in the console:
WebSocket connection to 'wss://hipm.test/app/24e751527b7716d6c2be?protocol=7&client=js&version=4.3.1&flash=false' failed: Error during WebSocket handshake: Unexpected response code: 404

stucked time to time

websockets are stucked time to time and not accepting connections. i'm not sure what can cause that behaviour
i have cloudflare > nginx > websocket
cloudflare not free plan so it works well, nginx time to time showing me bad gateway cuz he cant connect to websocket, nginx config:

server {
    listen 2053 ssl;
    server_name host.org www.host.org;

    ssl_certificate /etc/letsencrypt/live/host.org/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/host.org/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/host.org/chain.pem;

    ssl_stapling on;
    ssl_stapling_verify on;

    add_header Strict-Transport-Security "max-age=31536000";

    add_header Content-Security-Policy "img-src https: data:; upgrade-insecure-requests";

    location / {
	proxy_pass             http://127.0.0.1:6001;
	proxy_set_header Host  $host;
	proxy_read_timeout     1h;
	proxy_connect_timeout  5;
	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;
  }
}

SSL Not working

When connecting to the dashboard over https it works perfectly fine, but when I click on connect. I don't get connected and the console reports the following WebSocket connection to 'wss://socket.myapp.com:6001/app/my_key?protocol=7&client=js&version=4.3.1&flash=false' failed: WebSocket opening handshake timed out
My SSL configuration:

'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' => 'PATH_TO/cert.pem',

        /*
         * Path to local private key file on filesystem in case of separate files for
         * certificate (local_cert) and private key.
         */
        'local_pk' => 'PATH_TO/private.pem',

        /*
         * Passphrase for your local_cert file.
         */
        'passphrase' => null,
    ],

I am running this on a Vultr instance with PHP 7.2.10 and NGINX.

How can I resolve this issue?

Laravel Forge Configuration

I have the websocket server running locally and a separate also-local laravel instance can connect to it - the debug console shows the events. This is super cool - thank you for making this!

I have created an AWS EC2 instance using Forge and deployed that repo. I did the migrations, registered, etc. The web portion of the Laravel install seems to be working fine. Using Forge, I opened port 6001. The debug console comes up (and it correctly shows the names of the two apps I configured). If I connect to one of them, some items come up on the graph, but it does not show the private websocket Channel events and my attempts to trigger events through it silently fail.

Is there more configuration I need to do on AWS and/or Forge?

Thanks

send event form client

Hello

I found a way to send event from client:

Echo.connector.pusher.send_event(eventname, data, channel)

On Laravel side how can I handle this event?

Thank you

websocket serve stops working after a minute (ssl)

laravel/framework 5.7.19
beyondcode/laravel-websockets 1.0.3
php-fpm 7.2.12

I got everything working with ssl by following the very nice documentation.
Now when i start the websocket server everything seems to be working fine:

  • Dashboard connects and shows all subscriptions and so on
  • Client Browser subscribes to privat channel using laravel echo
  • Broadcast-Event reaches the client browser.
  • All good.

But after a minute it stops working. Dashboard looses connection. Reconnect results in:

  • Dashboard shows "Channels current state is unavailable".
  • Browser console says "WebSocket opening handshake timed out".
  • artisan output is:
    ´
    Connection id 17030417.641664442 sending message {"event":"pusher:connection_established","data":"{"socket_id":"17030417.641664442","activity_timeout":30}"}
    Connection id 17030417.641664442 closed.`

Are there any debugging possibilities? I can't see nothing atm...thanks !

laravel-websockets with Let's Encrypt

I have got the code working without SSL and it works as expected. I changed the code as follows to use my Let's Encrypt certificates but can not get it to work:

(I am running the code on a Debian 8 (Jessie) machine configured using ISPConfig)

added encrypted: true, to the Echo code:

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,
disableStats: true,
encrypted: true,
});

In the websockets.php file I added my certificates:

'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' => '/var/www/example.com/ssl/example.com-le.crt',
/

* Path to local private key file on filesystem in case of separate files for
* certificate (local_cert) and private key.
/
'local_pk' => '/var/www/example.com/ssl/example.com-le.key',
/

* Passphrase for your local_cert file.
*/
'passphrase' => null,
],

When I try to connect in Firefox (or Chrome) I get the following errors:

WebSocket connection to 'wss://example.com/app/f5d5d4fce53eec8a4f05?protocol=7&client=js&version=4.3.1&flash=false' failed: Error during WebSocket handshake: Unexpected response code: 404

then after this:

app.js:39131 WebSocket connection to 'wss://example.com/app/f5d5d4fce53eec8a4f05?protocol=7&client=js&version=4.3.1&flash=false' failed: WebSocket is closed before the connection is established.

My certificates are working as the page loads fine, it's just Echo does not seem to want to connect.

Is there a way to get more information from php artisan websockets:serve? I have tried adding --verbose at the end and it still shows 'Starting the WebSocket server on port 6001..' as normal. Even if I deliberately misspell the certificate name it shows the same message.

Dashboard in Production?

I'm trying to run the dashboard in production and limit its access to specific users but it looks like the $user var in Gate's definition is always null for some reason.

How can I run it with limited access to specific users?

P.S. I used the same code as in the docs. It appears there is no auth info in the request payload when the dashboard is running.

Not working along Botman

Botman and mpociot/slack-client are locking react/socket at v0.4.6 😢

composer require beyondcode/laravel-websockets
Using version ^1.0 for beyondcode/laravel-websockets
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)         
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for react/socket (locked at v0.4.6) -> satisfiable by react/socket[v0.4.6].
    - beyondcode/laravel-websockets 1.0.0 requires clue/buzz-react ^2.5 -> satisfiable by clue/buzz-react[v2.5.0].
    - beyondcode/laravel-websockets 1.0.1 requires clue/buzz-react ^2.5 -> satisfiable by clue/buzz-react[v2.5.0].
    - beyondcode/laravel-websockets 1.0.2 requires clue/buzz-react ^2.5 -> satisfiable by clue/buzz-react[v2.5.0].
    - clue/buzz-react v2.5.0 requires react/socket ^1.1 -> satisfiable by react/socket[v1.1.0].
    - Conclusion: don't install react/socket v1.1.0
    - Installation request for beyondcode/laravel-websockets ^1.0 -> satisfiable by beyondcode/laravel-websockets[1.0.0, 1.0.1, 1.0.2].


Installation failed, reverting ./composer.json to its original content.

how to make it work with Laravel Valet --secure

I am trying to get the demo to work and it is not. I figure it must be because by default all my valet sites use the --secure flag

I get this red error

screenshot 2018-12-05 02 20 45

I went into the websockets.php config file and tried to pass it the crt and key files:

    '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' => '/Users/xxx/.valet/Certificates/laravel-websockets-demo.dev.crt',
        // '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' => '/Users/xxx/.valet/Certificates/laravel-websockets-demo.dev.key',
        // 'local_pk' => null,

        /*
         * Passphrase with which your local_cert file was encoded.
         */
        'passphrase' => null
    ],

This changes the error and is no longer red, but it still doesn't work

screenshot 2018-12-05 02 20 29

Dashboard not showing any Events

should I configure the frontEnd in case I want to Monitoring the events on the laravel-websockets dashboard?I mean I need just to ensure that my event is broadcasted I don't want to listen it right now on the front-end because of testing purpose

Storing data to database when no connections are active

I have been testing laravel-websockets for a few days now and have noticed data being logged to the websockets_statistics_entries table even when no connections are being made.

Every time statistics are logged an entry is made in the table which over a few days grows pretty large. I can see there are options to limit the data recording rate and how long the data is stored for but I thought it might be handy if data was only stored if there was something to store.

Currently I have hundreds of lines similar to those shown below:

56 637707 0 0 1 2018-12-17 00:40:40 2018-12-17 00:40:40

These lines represent times when no connections are being made, this is a test server which only I have access to so I know that during the night no connections are made but I still get these lines of logged data.

This is just a thought and in no way a criticism of the code as I really think laravel-websockets is a great addition to Laravel.

How to use it over reverse proxy?

Hello,

I would like to use your package(and replace old laravel-echo-server), but it doesn't work if you need to connect to websocker service running in subdirectory....

for example something like this:
http://yourdomain.com/application_name/ws

I have configured nginx as reverse proxy to redirect any connection from http://yourdomain.com/application_name/ws to websocket running on 6001 . how to configure this URL in laravel-echo?

There is only wsHost and wsPort and I need something like this:

window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your-pusher-key',
wsUrl: 'http://yourdomain.com/application_name/ws',
disableStats: true,
});

Thx

BeyondCode\LaravelWebSockets\WebSockets\Exceptions\InvalidSignature

New connection opened for app key b9f65c07-3aaf-4c2d-8301-683c0a340365.
Connection id 908493867.947663013 sending message {"event":"pusher:connection_established","data":"{\"socket_id\":\"908493867.947663013\",\"activity_timeout\":30}"}
b9f65c07-3aaf-4c2d-8301-683c0a340365: connection id 908493867.947663013 received message: {"event":"pusher:subscribe","data":{"auth":":c113a4ecc6c9b6c7d75f98e701d01922011532150a26be624bf370cfa76e89fb","channel_data":"{\"user_id\":2,\"user_info\":true}","channel":"presence-App.User.2"}}.
Exception `BeyondCode\LaravelWebSockets\WebSockets\Exceptions\InvalidSignature` thrown: `Invalid Signature`
b9f65c07-3aaf-4c2d-8301-683c0a340365: exception `BeyondCode\LaravelWebSockets\WebSockets\Exceptions\InvalidSignature` thrown: `Invalid Signature`.
Connection id 908493867.947663013 sending message {"event":"pusher:error","data":{"message":"Invalid Signature","code":4009}}
{"auth":":c113a4ecc6c9b6c7d75f98e701d01922011532150a26be624bf370cfa76e89fb","channel_data":"{\"user_id\":2,\"user_info\":true}","channel":"presence-App.User.2"}}

The value of auth feels wrong. There is no data before the colon.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.