Laravel Echo事件广播无法在Listener上收到

时间:2017-04-30 11:48:13

标签: laravel laravel-5 laravel-5.4 laravel-echo

在Laravel广播的想法很棒,但很难弄清楚如何让它发挥作用。即使多次阅读文档,看了很多教程..也许我只是缺少一些小东西。谁知道呢?

以下代码我在Homestead的Laravel 5.4项目中运行:

# Event
class NewNumber implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public $number;

    public function __construct($number)
    {
        $this->number = $number;
    }

    public function broadcastOn()
    {
        return new Channel('pub-channel');
    }
}

# EventServiceProvider:
protected $listen = [
        'App\Events\NewNumber' => [
            'App\Listeners\DoSomeThingsWithNewNumber',
        ],
    ];

广播配置设置为Redis。我安装了Laravel Echo Server 并使用laravel-echo-server start运行此操作,并在控制台中查看[11:15:16 AM] - v7y-5DsMXHdBXcqzAAAA joined channel: pub-bingo

之类的内容

它创建了以下配置:

{
    "authHost": "http://localhost",
    "authEndpoint": "/broadcasting/auth",
    "clients": [],
    "database": "redis",
    "databaseConfig": {
        "redis": {},
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": null,
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": ""
}

在javascript中,我补充道:

import Echo from "laravel-echo";

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});

console.info(window.Echo.channel('pub-channel'));

window.Echo.channel('pub-channel')
    .listen('NewNumber', (e) => {
        console.info(e);
        alert('Something happened');
        console.log(e.number);
    });

Chrome中的控制台会显示.info以及有关该频道的信息。就我所见,一切看起来都很好。

但是没有发生什么,我是listen方法中的alert和console.loggin。

我有一个在不同浏览器中触发的URL,里面有这个: broadcast(new \App\Events\NewNumber(rand(1, 100));

应用程序在Laravel日志中记录了一些内容,当我触发该URL时它已成功完成:

[2017-04-30 11:38:44] local.INFO: Broadcasting [App\Events\NewNumber] on channels [pub-channel] with payload:
{
    "number": 54,
    "socket": null
}  

我也在运行php artisan queue:listen(QUEUE_DRIVER:数据库)。但数据库保持空白..

我真的无法弄清楚我错过了什么......缺少什么?!...

1 个答案:

答案 0 :(得分:0)

问题在于命名空间

window.Echo.channel('pub-channel')
.listen('.NewNumber', (e) => {
    console.info(e);
    alert('Something happened');
    console.log(e.number);
});

在NewNumber之前添加一个点,您可以在文档中了解更多信息:https://laravel.com/docs/5.3/broadcasting#namespaces