【问题标题】:Laravel Echo Doesn't connect to socket channelLaravel Echo 不连接到套接字通道
【发布时间】:2021-03-08 12:28:06
【问题描述】:

我希望当我的套接字连接打开时在我的welcome.blade.php 中增加一些值。

这是我的 EventClass:

// app/Events/TestEvent.php
class TestEvent implements ShouldBroadcast
{
   ...
   public function broadcastOn()
   {
       return new Channel('test');
   }
}

这是我的路线:

// routes/web.php
Route::get('/fire', function () {
   event(new \App\Events\TestEvent());
   return 'ok';
});

这是 bootstrap.js 中的 Echo 配置:

// resources/js/bootstrap.js
...
import Echo from "laravel-echo"
window.io = require('socket.io-client');

window.Echo = new Echo({
   broadcaster: 'socket.io',
   host: window.location.hostname + ':6001' // this is laravel-echo-server host
});

这是我的welcome.blade.php:

// resources/views/welcome.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel</title>
</head>
<body>

<script src="{{ asset('/js/app.js') }}"></script>
<script>
    Echo.channel('test')
        .listen('TestEvent', e => {
            console.log(e)
        })
</script>

</body>
</html>

但是当我触发 TestEvent 时,我的欢迎页面控制台是空的。

【问题讨论】:

    标签: php laravel websocket socket.io laravel-8


    【解决方案1】:

    由于您定义了broadcastOn 函数,您需要确保您实际上正在收听该频道名称。目前你正在监听的事件类名,这是你不提供broadcastOn函数时的默认通道名。

    因此,将您的 JavaScript 代码更改为收听 .test,并确保在名称前包含点!

    这里解释得很好:https://laravel.com/docs/8.x/broadcasting#broadcast-name

    【讨论】:

      猜你喜欢
      • 2018-11-10
      • 2023-03-21
      • 2021-03-12
      • 1970-01-01
      • 2019-03-05
      • 2017-09-06
      • 2017-10-17
      • 1970-01-01
      • 2020-07-05
      相关资源
      最近更新 更多