3
votes

Beyondcode Laravel Websockets: échec: WebSocket est fermé avant que la connexion ne soit établie

Les websockets locaux fonctionnent comme un charme, mais en production, je reçois toujours l'erreur dans le titre.

Quelques informations générales J'utilise le package websocket: Beyondcode / laravel-websockets. J'exécute 'php artisan websockets: serve --port = 6004' avec superviseur. Je me suis également assuré que le port 6004 est ouvert.

En production, j'ai essayé les paramètres avec et sans SSL, les deux ont donné l'erreur dans le titre.

Paramètres avec SSL:

Mes paramètres d'écho:

'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' => null,

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

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

    ],

Mes paramètres de poussoir:

'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' => false,
                'host' => '127.0.0.1',
                'port' => 6004,
                'scheme' => 'http',
            ],
        ],

Paramètres de mes websockets:

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    wsHost: window.location.hostname,
    wsPort: 6004,
    disableStats: true,
    enabledTransports: ['ws', 'wss'],
});

Paramètres sans SSL:

Mes paramètres d'écho:

'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' => base_path().'/ssl/server.crt',

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

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

Mes paramètres de poussoir:

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

Paramètres de mes websockets:

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    wsHost: window.location.hostname,
    wsPort: 6004,
    wssPort: 6004,
    disableStats: true,
    enabledTransports: ['ws', 'wss'],
});


0 commentaires

5 Réponses :


0
votes

Avez-vous essayé ces options dans la fenêtre "window.Echo"?

 host:          window.location.hostname,
 httpHost:      window.location.hostname,


1 commentaires

Ces jours-ci, j'ai vu beaucoup de questions sur le sujet Laravel Realtime .. Je prévois de faire un guide ou une vidéo à ce sujet demain avec Laravel 6. Si ce sera prêt, je mettrai ici le lien, mais j'espère que vous trouverez la solution avant cette..



1
votes

corrige le problème en ajoutant des chemins ssl dans websockets.php. J'utilise un ssl acheté que j'ai ajouté dans Plesk. Dans le cli, le chemin d'accès aux certificats est à partir de la racine: cd / usr / local / psa / var / certificates puis j'ai fait 'ls' pour vérifier les noms des certificats. Dans mon cas, j'ai utilisé le certificat avec la clé privée et ajouté en tant que chemin local_cert et chemin local_pk dans le fichier config / websockets.php

Paramètres finaux:

websockets.php

import Echo from 'laravel-echo'

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

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

diffusion.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'),
                'useTLS' => true,
                'host' => '127.0.0.1',
                'port' => 6004,
                'scheme' => 'https',
                 'curl_options' => [
                    CURLOPT_SSL_VERIFYHOST => 0,
                    CURLOPT_SSL_VERIFYPEER => 0,
                ]
            ],
        ],

bootstrap.js

'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' => 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('ssl_certificate', null),

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

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

btw n'oubliez pas d'exécuter npm run dev lorsque vous modifiez quelque chose dans bootstrap.js et que je l'exécute sur le port 6004 donc si vous l'exécutez sur 6001, n'oubliez pas de le modifier mes paramètres ci-dessus


0 commentaires

5
votes

donc après quelques jours de batailles avec ssl, je dois partager avec mes connaissances dans ce sujet .. Après l'installation selon docs, websockets a été travaillé avec http, mais pas après avoir utilisé ssl (443). Je pense que j'ai eu un problème avec les paramètres corrects et le chemin vers .pem (Let's Encrypt) (j'ai tout essayé, cela fonctionne pour moi). J'utilise les paramètres normaux pour Apatche2 mydomain.conf avec le port *: 443, sur le serveur VPS. 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' => true,
            'enable_statistics' => true,
            'encrypted' => true,
        ],
    ],
  'ssl' => [ 
        'local_cert' => '/etc/letsencrypt/live/server1.mydomain.com/fullchain.pem',
        'local_pk' => '/etc/letsencrypt/live/server1.mydomain.com/privkey.pem', 
        'passphrase' => null,
        'verify_peer' => false,
    ],
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' => 'server1.mydomain.com',
                'port' => 6001,
                'scheme' => 'https',
                'curl_options' => [
                    CURLOPT_SSL_VERIFYHOST => 0,
                    CURLOPT_SSL_VERIFYPEER => 0,
                ]
            ],
        ],  

Bootstrap.js:
  window.Echo = new Echo({
        auth:{ headers: { 'Authorization': 'Bearer ' + user.token } },
        broadcaster: 'pusher',
        key: process.env.MIX_PUSHER_APP_KEY,
        cluster: process.env.MIX_PUSHER_APP_CLUSTER,
        wsHost: window.location.hostname,
        wsPort: 6001,
        wssPort: 6001,
        disableStats: false, 
        enabledTransports: ['ws', 'wss']
 });

J'espère que cela vous sera utile. merci, bonne chance et à bientôt :)


2 commentaires

Vous êtes une bouée de sauvetage, cela a finalement fonctionné pour moi. Pour plus de clarté pour les futurs lecteurs - dans votre fichier de configuration apache, vous n'avez pas besoin d'utiliser le proxy pass ou rewriteengine vers ws: // ou wss: // (si le serveur de sockets est servi par cet hôte virtuel) - d'où "J'utilise normal settings pour Apatche2 mydomain.conf avec port *: 443 "Pour une preuve de concept, j'ai copié les fichiers de certificat dans le répertoire / config et je les ai mis à www-data. Quant à la solution finale, vous pouvez copier les fichiers et les recopier à chaque fois que vous renouvelez le certificat ou accordez des autorisations aux fichiers (la liaison symbolique ne semble pas fonctionner).


mec, tu m'as sauvé la vie. Cette réponse est ce que je cherchais :). Merci youuuu.



5
votes

Dans mon cas, après avoir rétrogradé le poussoir de 6 quelque chose à

"pusher-js": "^4.3.1"

cela a commencé à fonctionner. Javascript je t'aime! ðŸ˜


2 commentaires

où dois-je mettre ceci ou comment dois-je rétrograder? J'ai vérifié le fichier composer.json mais je n'ai rien trouvé


pusher-js c'est un paquet npm. Vous l'avez dans package.json



1
votes

J'ai également rencontré ce problème et publié une question plus détaillée où je vous ai montré les paramètres du pare - feu , laravel , nuxt , nginx et websockets . Quelques jours plus tard, une solution a été trouvée: Laravel + Nuxt + Nginx: WebSocket est fermé avant que la connexion ne soit établie

For comparison, see also the question itself on the link above.

Paramètres du projet

Pare-feu

netstat -ntlp | grep ECOUTER

server {
        server_name     larastart.site;
        root            /var/www/api/public;

        add_header X-Frame-Options              "SAMEORIGIN";
        add_header X-XSS-Protection             "1; mode=block";
        add_header X-Content-Type-Options       "nosniff";

        # Priority file extensions
        index index.php index.html index.htm index.nginx-debian.html;

        charset utf-8;

        # Check for the existence of files matching a provided url, forward to 404 if not found
        location /api {
                try_files $uri $uri/ /index.php?$query_string;
        }

        # Serve static files directly
        location ~* ^/storage/(.*)\.(jpg|jpeg|gif|bmp|png|ico)$ {
                access_log off;
        }

        location / {
                proxy_pass                          http://127.0.0.1:3000;
                proxy_set_header Host               $host;
                proxy_set_header X-Real-IP          $remote_addr;

                proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto  $scheme;
                proxy_set_header X-VerifiedViaNginx yes;
                proxy_read_timeout                  300;
                proxy_connect_timeout               300;
        }

        location /app {
                proxy_pass             https://larastart.site: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;
        }

        error_page 404 /index.php;

        # pass PHP scripts to FastCGI server
        location ~ \.php$ {
                fastcgi_pass  unix:/var/run/php/php7.4-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
                include fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root concurs with nginx's one
        location ~ /\.(?!well-known).* {
               deny all;
        }

        listen 443 ssl; # managed by Certbot

        ssl_certificate     /etc/letsencrypt/live/larastart.site/fullchain.pem;     # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/larastart.site/privkey.pem;       # managed by Certbot
        include             /etc/letsencrypt/options-ssl-nginx.conf;                # managed by Certbot
        ssl_dhparam         /etc/letsencrypt/ssl-dhparams.pem;                      # managed by Certbot
}

server {
        if ($host = larastart.site) {
                return 301 https://$host$request_uri;
        } # managed by Certbot

        listen 80;
        server_name larastart.site;
        return 404; # managed by Certbot
}

lsof -i -P -n | grep ECOUTER

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}


#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

statut ufw

import Echo from 'laravel-echo';

export default (app) => {
    window.Pusher = require('pusher-js');

    window.Echo = new Echo({
        broadcaster: process.env.BROADCAST_DRIVER,
        key: process.env.PUSHER_APP_KEY,
        cluster: process.env.PUSHER_APP_CLUSTER,

        forceTLS: true,
        encrypted: false,
        wsHost: window.location.hostname,
        wsPort: 6001,
        wssPort: 6001,
        disableStats: true,
        enabledTransports: ['ws', 'wss']
    });
}

ufw show écoute

{
  "name": "frontend",
  "version": "1.0.0",
  "private": true,
  "config": {
    "nuxt": {
      "port": "3000"
    }
  },
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "export": "nuxt export",
    "serve": "nuxt serve"
  },
  "dependencies": {
    "@nuxtjs/axios": "^5.12.2",
    "@nuxtjs/dotenv": "^1.4.1",
    "@nuxtjs/laravel-echo": "^1.1.0",
    "@nuxtjs/proxy": "^2.0.1",
    "nuxt": "^2.13.0",
    "pusher-js": "^4.4.0"
  },
  "devDependencies": {}
}

Laravel

vim /var/www/api/config/websockets.php

...
    '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'),
                'useTLS' => true,
                'encrypted' => false,
                'host' => '127.0.0.1',
                'port' => 6001,
                'scheme' => 'https',
                'curl_options' => [
                        CURLOPT_SSL_VERIFYHOST => 0,
                        CURLOPT_SSL_VERIFYPEER => 0,
                ]

            ],
        ],
...
    ],
...

vim /var/www/api/config/broadcasting.php

...
    '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' => true,
            'enable_statistics' => false,
        ],
    ],
...
    'ssl' => [
        'local_cert' => '/etc/letsencrypt/live/larastart.site/fullchain.pem',
        'local_pk' => '/etc/letsencrypt/live/larastart.site/privkey.pem',
        'passphrase' => null,
        'verify_peer' => false
    ],
...

Nuxt

vim /var/www/client/package.json

root@dsde1032-21892:~# ufw show listening
tcp:
  22 * (sshd)
   [ 1] allow OpenSSH

  443 * (nginx)
   [ 2] allow 'Nginx Full'

  6001 * (php7.4)
   [ 3] allow 6001

  80 * (nginx)
   [ 2] allow 'Nginx Full'

tcp6:
  22 * (sshd)
   [ 4] allow OpenSSH

vim /var/www/client/plugins/echo.js

root@dsde1032-21892:~# ufw status
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
Nginx Full                 ALLOW       Anywhere
6001                       ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)
Nginx Full (v6)            ALLOW       Anywhere (v6)
6001 (v6)                  ALLOW       Anywhere (v6)

Nginx

vim /etc/nginx/nginx.conf

root@dsde1032-21892:~# lsof -i -P -n | grep LISTEN
sshd     1064     root    3u  IPv4  20044      0t0  TCP *:22 (LISTEN)
sshd     1064     root    4u  IPv6  20138      0t0  TCP *:22 (LISTEN)
nginx    1066     root    6u  IPv4  20168      0t0  TCP *:443 (LISTEN)
nginx    1066     root    7u  IPv4  20169      0t0  TCP *:80 (LISTEN)
mysqld   1078    mysql   31u  IPv4  20463      0t0  TCP 127.0.0.1:3306 (LISTEN)
node     1173     root   18u  IPv4  20902      0t0  TCP 127.0.0.1:3000 (LISTEN)
nginx    7402 www-data    6u  IPv4  20168      0t0  TCP *:443 (LISTEN)
nginx    7402 www-data    7u  IPv4  20169      0t0  TCP *:80 (LISTEN)
php      7768     root    5u  IPv4 110549      0t0  TCP *:6001 (LISTEN)

vim /etc/nginx/sites-available/larastart.site

root@dsde1032-21892:~# netstat -ntlp | grep LISTEN
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1066/nginx: master
tcp        0      0 0.0.0.0:6001            0.0.0.0:*               LISTEN      7768/php
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1064/sshd
tcp        0      0 127.0.0.1:3000          0.0.0.0:*               LISTEN      1173/node
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      1066/nginx: master
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      1078/mysqld
tcp6       0      0 :::22                   :::*                    LISTEN      1064/sshd


0 commentaires