The issue is with connecting to the socket server in Laravel using Laravel Echo

119 Views Asked by At

"I am working on a project using Laravel Broadcast and the package beyondcode/laravel-websockets. When I use Pusher.js directly, the connection and operations are successful, but when I use Laravel Echo, there is no connection established with the socket server."

in file js:

pusher code:
Pusher.logToConsole = true;
var pusher = new Pusher('a12bc34', {
    cluster: 'mt1',
    encrypted: false,
    forceTLS: false,
    wsHost: '127.0.0.1',
    wsPort: 6001,
});

var channel = pusher.subscribe('internal-transfer-forms');
channel.bind('eventInternalTransferForm', function (data) {
   
});
laravel echo code:
import Echo from 'laravel-echo';

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

window.Pusher.logToConsole = true;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'a12bc34',
    cluster: 'mt1',
    encrypted: false,
    wsHost: '127.0.0.1',
    wsPort: 6001,
    forceTLS: false,
});

Echo.channel(`internal-transfer-forms`)
    .listen('eventInternalTransferFormd', (e) => {
       
    });

"Based on the research I conducted and the question I asked in Telegram groups, unfortunately, I couldn't find the solution myself. It seems that the issue is more related to data transmission than connection, as I'm not even able to establish a connection. However, with Pusher.js, the connection and operations are successful."

2

There are 2 best solutions below

9
Jydipsinh Parmar On

Please check below status Step 1 :

Command : php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"

Step 2 :

php artisan migrate

Step 3 : You need to publish the WebSocket configuration file:

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

Step 4

composer require pusher/pusher-php-server

Step 5

Http

BROADCAST_DRIVER=pusher

PUSHER_APP_ID={yourid}

PUSHER_APP_KEY={yourKey}

PUSHER_APP_SECRET={yourKeySecret}

PUSHER_HOST=

PUSHER_PORT=

PUSHER_SCHEME=

PUSHER_APP_CLUSTER=mt1

REDIS_PREFIX=

LARAVEL_WEBSOCKETS_PORT=6001

If you are using https then change below thing in .env

Https

BROADCAST_DRIVER=pusher


PUSHER_APP_ID={yourid}

PUSHER_APP_KEY={yourKey}

PUSHER_APP_SECRET={yourKeySecret}

PUSHER_HOST=

PUSHER_PORT=

PUSHER_SCHEME=

PUSHER_APP_CLUSTER=mt1

REDIS_PREFIX=

//for this parameter added if are using https give you ssl certificate path

LARAVEL_WEBSOCKETS_SSL_LOCAL_CERT = /var/www/html/b_laravel/ssl_cert/apache-selfsigned.pem

LARAVEL_WEBSOCKETS_SSL_LOCAL_PK   = /var/www/html/b_laravel/ssl_cert/apache-selfsigned-key.pem

LARAVEL_WEBSOCKETS_SSL_PASSPHRASE = ""

LARAVEL_WEBSOCKETS_PORT=6001

config/broadcasting.php

In this if Two way Setup if you are using http then socket work on ws and if you are using https Wss

1)If You are using Http then below change in your config/broadcasting.php file

Reference site : https://beyondco.de/docs/laravel-websockets/basic-usage/pusher

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

    ],

],

2)If You are using Https then below change in your config/broadcasting.php file

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

            'port' => 6001,       

            'scheme' => 'https',

            'debug' => true,

            'useTLS' => true,

            'curl_options' => [

            CURLOPT_SSL_VERIFYHOST => 0,

            CURLOPT_SSL_VERIFYPEER => 0,

            ]

    ],


'client_options' => [

    'verify' => false,

    // Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html

],

Step 6 config/websockets.php

1)If You are using Http then below change in your config/websockets.php file




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

        ],
 2)If You are using Https then below change in your config/websockets.php file




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

        ],

In ssl part you have to add below three parameter

1)verify_peer 2)verify_peer_name 3)allow_self_signed

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

        'verify_peer_name' => false,

        'allow_self_signed' => true,

    ],

Step 7

routes/web.php

Add this line



Route::post('/broadcasting/auth', function () {

    return Auth::user();

    });

Step 8 config/app.php

In order to turn on broadcasting for any Laravel application, we need to go to config/app.php and uncomment:


App\Providers\BroadcastServiceProvider::class,

Step 9

npm install --save laravel-echo pusher-js

Step 10 Change in resources/js/bootstrap.js

import axios from 'axios';

window.axios = axios;


let token = document.head.querySelector('meta[name="csrf-token"]');


if (token) {

    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;

} else {

    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');

}



window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';


/**

 * Echo exposes an expressive API for subscribing to channels and listening

 * for events that are broadcast by Laravel. Echo and event broadcasting

 * allows your team to easily build robust real-time web applications.

 */


import Echo from 'laravel-echo';


import Pusher from 'pusher-js';



window.Pusher = Pusher;

//console.log(window.location.hostname);

window.Echo = new Echo({

    broadcaster: 'pusher',

    key: '{yourKey}',

    cluster: 'mt1',

    wsHost: window.location.hostname,

    wsPort: 6001,

    wssPort: 6001,

    forceTLS: true,

    disableStats: true,

    

});


If you are using http then you to connect using below code
window.Pusher = Pusher;

window.Echo = new Echo({

    broadcaster: 'pusher',

    key: '{yourKey}',

    cluster: 'mt1',

    wsHost: window.location.hostname,

    wsPort: 6001,

    wssPort: 6001,

    forceTLS: false,

    disableStats: true,

    

});

Please checked how to install supervioser and virtulhost in laravel websocket Please check link. laravel websocket setup and example how to use it

0
Jydipsinh Parmar On
<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Illuminate\Support\Facades\Redirect;

use Pusher\Pusher;

class ChatController extends Controller

{

    public function index()

    {

        return view('chat');

    }

    public function sendmessage(Request $request)

    {

        //dd($request->all());

        $sendData['name'] = $request->your_name;

        $sendData['message'] = $request->send_meesage;

        $paramater['chanel'] = "guest_user";

        $paramater['event'] = "ChatEvent";

        $paramater['data'] = $sendData;

        try {

        $pusher = new Pusher(

            

            config('broadcasting.connections.pusher.key'),

            config('broadcasting.connections.pusher.secret'),

            config('broadcasting.connections.pusher.app_id'),

            config('broadcasting.connections.pusher.options', []),

             new \GuzzleHttp\Client(['verify' => false]),

        );      

           $pusher->trigger($paramater['chanel'], $paramater['event'], $paramater['data']);

        } catch (Exception $e) {

        // Handle Pusher API error

            // You might log the error, notify administrators, or respond to the client accordingly

          dd($e->getMessage());

        }

        return Redirect::to('/chat')->with(['type' => 'success','message' => 'Your message sent sucessfully']);

    }

    public function getmessage()

    {

        return view('get_message');

    }

}

For message or change sent to laravel websocket add name space :

use Pusher\Pusher;

in your controller

$sendData['name'] = $request->your_name;

        $sendData['message'] = $request->send_meesage;

        $paramater['chanel'] = "guest_user";

        $paramater['event'] = "ChatEvent";

        $paramater['data'] = $sendData;

        try {

        $pusher = new Pusher(



            config('broadcasting.connections.pusher.key'),

            config('broadcasting.connections.pusher.secret'),

            config('broadcasting.connections.pusher.app_id'),

            config('broadcasting.connections.pusher.options', []),

             new \GuzzleHttp\Client(['verify' => false]),

        );      

           $pusher->trigger($paramater['chanel'], $paramater['event'], $paramater['data']);

        } catch (Exception $e) {

        // Handle Pusher API error

            // You might log the error, notify administrators, or respond to the client accordingly

          dd($e->getMessage());

        }
you can send your data using above example. i think you have to use laravel boardcast event but i facing same issue so i have solution above example