Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Echo callback

I'm looking into Laravel Echo (With socket.io as connector)

But I can't find out how to bind a callback when user/visitor succeed or not connecting to the socket (Not channel), but generally if connected.

import Echo from "laravel-echo"; //import Laravel-echo

if(typeof(io) != 'undefined'){ //check if io loaded
    //init Echo
    window.Echo = new Echo({
        broadcaster: 'socket.io',
        host: { path: '/socket.io' }
    });
}

So here I do check if io exist, then most probably socket is up.

But can we bind a callback like we can do with socket.io: Example from socket.io docs

const socket = io('http://localhost');

console.log(socket.id); // undefined

socket.on('connect', () => {
  console.log(socket.id); // 'here we can get socket id'
});

The reason why I need a callback is to get the socket id and initiate other scripts.

like image 567
Froxz Avatar asked Sep 22 '17 08:09

Froxz


People also ask

What is echo in Laravel?

Laravel Echo is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by your server-side broadcasting driver. You may install Echo via the NPM package manager. In this example, we will also install the pusher-js package.

Is Laravel echo free?

Socket servers usually were not that easy to setup, but Laravel Echo Server changes this. This is completely free, you only have to run the socket server yourself.

What is pusher in Laravel?

Pusher Channels acts as a realtime layer between your client and server events, maintaining persistent connections to the clients.


1 Answers

Looking deeper into the laravel echo source code, I've found that there is on event binder, that we can't call straight away echo.on('connect', ...). But we have access to connector and the actual socket so here is the solution:

if(typeof(io) != 'undefined'){ //check if io loaded
    //init Echo
    echo = new Echo({
        broadcaster: 'socket.io',
        host: { path: '/socket.io' }
    });

    //bind our events
    echo.connector.socket.on('connect', function(){
        console.log('connected', echo.socketId());
    });
    echo.connector.socket.on('disconnect', function(){
        console.log('disconnected');
    });
    echo.connector.socket.on('reconnecting', function(attemptNumber){
        console.log('reconnecting', attemptNumber);
    });
}
like image 135
Froxz Avatar answered Sep 19 '22 13:09

Froxz