Laravel Echo回调

问题描述 投票:1回答:2

我正在研究Laravel Echo(使用socket.io作为连接器)

但是,当用户/访问者成功或未连接到套接字(非通道)时,我无法找到如何绑定回调,但通常是连接时。

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' }
    });
}

所以我在这里检查io是否存在,然后很可能socket已经启动了。

但是我们可以绑定一个回调,就像我们可以用socket.io做的那样:来自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'
});

我需要回调的原因是获取套接字ID并启动其他脚本。

php laravel-5 socket.io laravel-5.5 laravel-echo
2个回答
6
投票

仔细研究laravel回声源代码,我发现有on事件活页夹,我们不能马上打电话给echo.on('connect', ...)。但我们可以访问连接器和实际的套接字,所以这里是解决方案:

 if(typeof(io) != 'undefined'){ //check if io loaded
    //init Echo
    echo = new Echo({
        broadcaster: 'socket.io',
        host: { path: '/socket.io' }
    });
}
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);
});

1
投票

对于任何试图找出如何从Presence频道here连接返回承诺的人,以下内容对我有用:

// return a promise and resolve when the subscription has succeeded
return new Promise((resolve, reject) => {
    echo.connector.channels['presence-' + channel].subscription.bind('pusher:subscription_succeeded', () => {
        return resolve(true);
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.