pusher_client icon indicating copy to clipboard operation
pusher_client copied to clipboard

Flutter + Laravel Websocket + Pusher Replacement (Valet Secure)

Open lambasoft opened this issue 3 years ago • 22 comments

I'm using Beyondco Larevel Websockets on my Laravel Backend, and using pusher_client and laravel_echo on my Flutter frontend.

I've been trying to connect from my ios simulator into my Laravel Backend host, which is using valet secure, but failing.

My Flutter connections:


PusherClient getPusherClient(String token) {
  PusherOptions options = PusherOptions(
      host: 'my-local-server.test',
      wsPort: 6001,
      wssPort: 6001,
      cluster: DotEnv.env['PUSHER_APP_CLUSTER'],
      encrypted: true,
      auth: PusherAuth('https://my-local-server.test/api/broadcasting/auth',
          headers: {'Authorization': 'Bearer $token'})
  );

  return PusherClient(DotEnv.env['PUSHER_APP_KEY'], options,
      enableLogging: true, autoConnect: false);
}
pusherClient = getPusherClient(token);
pusherClient.connect();
pusherClient.onConnectionStateChange((state) {
  print(
      "previousState: ${state.previousState}, currentState: ${state.currentState}");
});
pusherClient.onConnectionError((error) {
  print(error.message);
});

From https://my-local-server.test/laravel-websockets I never see the requests from Flutter, but if I fire an event from my Laravel backend, it gets logged.

Please help me with what's wrong in my setup, why I can't connect to my SSL valet server running laravel-websocket from my Flutter application.

lambasoft avatar May 14 '21 16:05 lambasoft

same here! .It seems like this plug in is incompatible with laravel self hosted pusher websocket server although it says in documentation that it work. @chinloyal

soewaiyanmyowin avatar May 18 '21 10:05 soewaiyanmyowin

I'm ready to offer a paid bounty on that. I'm still having the problem

lambasoft avatar May 18 '21 12:05 lambasoft

I'm ready to offer a paid bounty on that. I'm still having the problem

Me too! @chinloyal @spiritinlife

soewaiyanmyowin avatar May 19 '21 04:05 soewaiyanmyowin

Ok, here how it worked for me: 1- I used Laravel Sanctum for Authentication 2- Inside laravel BraodCastServiceProvider added the following: image 3- in the Flutter App i did the following: image and it works for the Private channels

muhammadessam avatar Jun 06 '21 12:06 muhammadessam

Ok, here how it worked for me: 1- I used Laravel Sanctum for Authentication 2- Inside laravel BraodCastServiceProvider added the following: image 3- in the Flutter App i did the following: image and it works for the Private channels

Thz man

soewaiyanmyowin avatar Jun 06 '21 13:06 soewaiyanmyowin

guys i am facing the same problem, i am able to connect the socket from my web application but from flutter, it keep saying connection/reconnection and i do not see any stats in WebSocket dashboard at all

UnifySoftTech avatar Jun 09 '21 08:06 UnifySoftTech

guys i am facing the same problem, i am able to connect the socket from my web application but from flutter, it keep saying connection/reconnection and i do not see any stats in WebSocket dashboard at all

  • For the connecting reconnecting problem remove the cluster from your flutter app
  • If you followed the step above it will work for the flutter but won't work for the web
  • i think you can add the web middleware to the broadcast routes method

@UnifySoftTech

muhammadessam avatar Jun 10 '21 21:06 muhammadessam

@muhammadessam Thanks for the response, let me check this when i get to office and will update you here. Otherwise, i will share my code for a better explanation

UnifySoftTech avatar Jun 11 '21 03:06 UnifySoftTech

  1. This is my Broadcast.php file `<?php

return [

/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
| Supported: "pusher", "ably", "redis", "log", "null"
|
*/

'default' => env('BROADCAST_DRIVER', 'null'),

/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/

'connections' => [

    'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [

            'encrypted' => true,
            'host' => 'my-laravel-domain.com',
            'port' => 6002,
            'scheme' => 'https',
            'curl_options' => [
                 CURLOPT_SSL_VERIFYHOST => 0,
                 CURLOPT_SSL_VERIFYPEER => 0,
             ]
        ],
       
    ],

    'ably' => [
        'driver' => 'ably',
        'key' => env('ABLY_KEY'),
    ],

    'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
    ],

    'log' => [
        'driver' => 'log',
    ],

    'null' => [
        'driver' => 'null',
    ],

],

]; 2. This is my Websockets.php<?php

use BeyondCode\LaravelWebSockets\Dashboard\Http\Middleware\Authorize;

return [

/*
 * Set a custom dashboard configuration
 */
'dashboard' => [
    'port' => env('LARAVEL_WEBSOCKETS_PORT', 6002),
],

/*
 * This package comes with multi tenancy out of the box. Here you can
 * configure the different apps that can use the webSockets server.
 *
 * Optionally you specify capacity so you can limit the maximum
 * concurrent connections for a specific app.
 *
 * Optionally you can disable client events so clients cannot send
 * messages to each other via the webSockets.
 */
'apps' => [
    [
        'id' => env('PUSHER_APP_ID'),
        'name' => env('APP_NAME'),
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'path' => env('PUSHER_APP_PATH'),
        'capacity' => null,
        'enable_client_messages' => false,
        'enable_statistics' => true,
    ],
],

/*
 * This class is responsible for finding the apps. The default provider
 * will use the apps defined in this config file.
 *
 * You can create a custom provider by implementing the
 * `AppProvider` interface.
 */
'app_provider' => BeyondCode\LaravelWebSockets\Apps\ConfigAppProvider::class,

/*
 * This array contains the hosts of which you want to allow incoming requests.
 * Leave this empty if you want to accept requests from all hosts.
 */
'allowed_origins' => [
    //
],

/*
 * The maximum request size in kilobytes that is allowed for an incoming WebSocket request.
 */
'max_request_size_in_kb' => 250,

/*
 * This path will be used to register the necessary routes for the package.
 */
'path' => 'laravel-websockets',

/*
 * Dashboard Routes Middleware
 *
 * These middleware will be assigned to every dashboard route, giving you
 * the chance to add your own middleware to this list or change any of
 * the existing middleware. Or, you can simply stick with this list.
 */
'middleware' => [
    'web',
    Authorize::class,
],

'statistics' => [
    /*
     * This model will be used to store the statistics of the WebSocketsServer.
     * The only requirement is that the model should extend
     * `WebSocketsStatisticsEntry` provided by this package.
     */
    'model' => \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry::class,

    /**
     * The Statistics Logger will, by default, handle the incoming statistics, store them
     * and then release them into the database on each interval defined below.
     */
    'logger' => BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger::class,

    /*
     * Here you can specify the interval in seconds at which statistics should be logged.
     */
    'interval_in_seconds' => 60,

    /*
     * When the clean-command is executed, all recorded statistics older than
     * the number of days specified here will be deleted.
     */
    'delete_statistics_older_than_days' => 60,

    /*
     * Use an DNS resolver to make the requests to the statistics logger
     * default is to resolve everything to 127.0.0.1.
     */
    'perform_dns_lookup' => false,
],

/*
 * Define the optional SSL context for your WebSocket connections.
 * You can see all available options at: http://php.net/manual/en/context.ssl.php
 */
'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('LARAVEL_WEBSOCKETS_SSL_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('LARAVEL_WEBSOCKETS_SSL_LOCAL_PK', null),

    /*
     * Passphrase for your local_cert file.
     */
    'passphrase' => env('LARAVEL_WEBSOCKETS_SSL_PASSPHRASE', null),
    
    'verify_peer' => false,
],

/*
 * Channel Manager
 * This class handles how channel persistence is handled.
 * By default, persistence is stored in an array by the running webserver.
 * The only requirement is that the class should implement
 * `ChannelManager` interface provided by this package.
 */
'channel_manager' => \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManagers\ArrayChannelManager::class,

];`

  1. I have added my SSL Certificates in the .env file and set Broadcast driver to pusher. I have laravel chat application setup on my localhost and i can connect to this socket from that application and everything works just fine but from my flutter application, i can not connect to socket at all.

  2. I have added this route into my api.php Broadcast::routes(['middleware' => ['auth:api']]);

5.Here is my Flutter code `ws-ap2.pusherapp.com

/*static Echo echoSetup(token, pusherClient) { return new Echo({ 'broadcaster': 'pusher', 'key': 'apikey', 'client': pusherClient, "wsHost": 'my-larave-domain.com', "httpHost": 'my-larave-domain.com', "wsPort": 6002, "wssPort": 6002, 'auth': { "headers": {'Authorization': 'Bearer $token'} }, 'authEndpoint': 'my-larave-domain.com/api/broadcasting/auth', "disableStats": true, "forceTLS": false, "enabledTransports": ['ws', 'wss'] }); }

static FlutterPusher getPusherClient(String token) { PusherOptions options = PusherOptions( encrypted: false, host: 'chabbi.unifysofttech.in', port: 6002, auth: PusherAuth( 'https://my-larave-domain.com/api/broadcasting/auth', headers: {'Authorization': 'Bearer $token'}, ), ); return FlutterPusher( 'apikey', options, enableLogging: true, lazyConnect: true, onError: (e) { print("onError: ${e.message}"); }, ); }*/`

Any help is appriciated. Thanks

UnifySoftTech avatar Jun 11 '21 05:06 UnifySoftTech

guys i am facing the same problem, i am able to connect the socket from my web application but from flutter, it keep saying connection/reconnection and i do not see any stats in WebSocket dashboard at all

  • The host in pusher options is different
  • and please check what happens in your laravel websockts dashboard, is there a connection made or not
  • are you using laravel sanctum or something else

muhammadessam avatar Jun 13 '21 09:06 muhammadessam

#The host name i added in these files is dummy to paste here otherwise it is correct on my production server.

if i connect from my laravel chat application it does gets connected but from flutter nothing shows in the dashboard as well.

I am using JWT

UnifySoftTech avatar Jun 13 '21 11:06 UnifySoftTech

try using sanctum @UnifySoftTech

muhammadessam avatar Jun 14 '21 17:06 muhammadessam

Im not able to connect (CONNECTING, DISCONNECTED, RECONNECTING...)to my laravel-websockets server on local machine using vvalet domain name or computer IP. I tested throught vuejs and it work fine Valet is on mydomain.test ` wsHost = '192.168......'; //or localhost FlutterPusher getPusherClient() { PusherOptions options = PusherOptions( host: wsHost, wssPort: 6001, encrypted: true, cluster: 'us3'); return PusherClient(pusherAppKey, options, lazyConnect: true, enableLogging: true); }

echo = new Echo({ 'broadcaster': 'pusher', 'client': pusherClient, "wsHost": wsHost, "httpHost": wsHost, "wsPort": 6001, 'auth': { "headers": {'Authorization': 'Bearer $token'} }, 'authEndpoint': 'https://$wsHost/api/broadcasting/auth', "disableStats": true, "forceTLS": true, "enabledTransports": ['ws', 'wss'] });

`

@chinloyal @spiritinlife

Can anyone help me ?

arlandclaudel avatar Jun 15 '21 09:06 arlandclaudel

@lambasoft Have you tried setting in your plist file:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

chinloyal avatar Aug 13 '21 08:08 chinloyal

Not working in flutter as well. My other package flutter_pusher_client is working fine though.

nicolasvahidzein avatar Sep 14 '21 16:09 nicolasvahidzein

Ok, here how it worked for me: 1- I used Laravel Sanctum for Authentication 2- Inside laravel BraodCastServiceProvider added the following: image 3- in the Flutter App i did the following: image and it works for the Private channels

I canot run web sockets on 433 port on vps / supervisior can u show us ur laravel full config settings , thnx

mosaw avatar Oct 17 '21 14:10 mosaw

try this:

https://github.com/olubunmitosin/laravel_flutter_pusher

and it was a BREEZE! Stop using this one.

nicolasvahidzein avatar Nov 02 '21 19:11 nicolasvahidzein

Did you solve it using (SSL) ?

YassineChe avatar Jul 26 '22 23:07 YassineChe

@YassineChe no, not with SSL did not try.

nicolasvahidzein avatar Aug 12 '22 20:08 nicolasvahidzein

@nicolasvahidzein I switched to this package dart_pusher_channels, No errors on IOS... And the owner active with the issues.

YassineChe avatar Aug 13 '22 02:08 YassineChe

@YassineChe NO WAY!!! You are the best. And this works with laravel websockets and flutter echo?

Can you share your code please? I'll try it right now i am blocked for a week on mac and i cannot release my app. If you have skype it would be nice to chat too: nzein19 is my handle. Cheers mate.

nicolasvahidzein avatar Aug 13 '22 07:08 nicolasvahidzein

Hello, @nicolasvahidzein I test it with Laravel websockets replacement and i didn't test it flutter echo, Sure, but don't have Skype just email me here '[email protected]' (Via Google meet) and we will fix a time.

YassineChe avatar Aug 13 '22 16:08 YassineChe