以下代码我在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:数据库)。但数据库保持空白..
我真的无法弄清楚我错过了什么......缺少什么?!...
答案 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