要在频道上播放活动,我使用了laravel Echo , redis 和 socket-io 。
这是我的活动:
class ChatNewMessage implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $targetUsers;
public $message;
public function __construct ($message)
{
$this->targetUsers = $message->chat->users->pluck('user_id');
$this->message = $message;
}
public function broadcastOn ()
{
$userChannels = [];
foreach ($this->targetUsers as $id) {
$userChannels[] = 'user-channel.' . $id;
}
return $userChannels;
}
public function broadcastAs()
{
return 'NewMessage';
}
}
对于Socket.io服务器,我使用laravel-echo-server,以下是配置:
{
"authHost": "http://api.pars-app.dev",
"authEndpoint": "/broadcasting/auth",
"clients": [
{
"appId": "1924bf1d59b3759d",
"key": "eaf9e3c843493421f4be488fba11f49d"
}
],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": "127.0.0.1",
"port": "3000",
"protocol": "http",
"socketio": {},
"sslCertPath": "",
"sslKeyPath": ""
}
这是bootstrap.js
文件中的Echo结构:
import Echo from "laravel-echo";
window.echo = new Echo({
broadcaster: 'socket.io',
host: 'http://127.0.0.1:3000',
auth: {
headers: {
Authorization: 'bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjUsImlzcyI6Imh0dHA6XC9cL2FwaS5wYXJzLWFwcC5kZXZcL3YxXC9hdXRoXC9zaWduSW4iLCJpYXQiOjE0ODkzMTY1ODgsImV4cCI6MTQ5MTkwNDk4OCwibmJmIjoxNDg5MzE2NTg4LCJqdGkiOiIwNzdiN2NjYjNlODE4MDU2NjBiMWNjYTkzZjI1ZTZmMyJ9.Y_BvVnJIq8k3uN1sQQuBna1CcLsrn7VnpH3RxXS8JEQ'
}
}
});
echo.channel('user-channel.5').listen('NewMessage', (e) => {
console.log(e);
});
运行laravel-echo-server和call事件后,下面的日志显示在控制台中,显示事件广播到频道:
[2:26:05 PM] - Xt_VSaSRHirHHxtUAAAE left channel: user-channel.5 (transport close)
[2:26:06 PM] - FwfOFMZqfrI9_H11AAAF joined channel: user-channel.5
Channel: user-channel.2
Event: NewMessage
CHANNEL user-channel.2
Channel: user-channel.1
Event: NewMessage
CHANNEL user-channel.1
Channel: user-channel.5
Event: NewMessage
CHANNEL user-channel.5
但是Echo无法听取频道和发生的事件。
什么是问题?
答案 0 :(得分:4)
我找到了解决方案。
根据this comment github页面上的laravel-echo-server,事件名称需要以点为前缀。像这样:
echo.channel('user-channel.5').listen('.NewMessage', (e) => {
console.log(e);
});
答案 1 :(得分:0)
Laravel Horizon显示成功消息时,我几天都遇到过同样的问题:
[2019-07-18 15:18:50][123] Processing: App\Events\EventClass
[2019-07-18 15:18:50][123] Processed: App\Events\EventClass
并且Laravel Echo Server也显示成功消息:
[5:18:27 PM] - xxxxxxxxxx left channel: laravel_database_testChannel (transport close)
[5:18:28 PM] - xxxxxxxxxx joined channel: laravel_database_testChannel
Channel: laravel_database_testChannel
Event: App\Events\EventClass
下面是我在broadcastOn()
中的EventClass
函数的样子:
public function broadcastOn()
{
return new Channel('testChannel');
}
如您所见,我在testChannel
频道中广播了我的活动。但是频道名称的前缀是laravel_database_
。
提示!因此,要找到合适的频道名称,您应该在Laravel Echo Server消息中找到它。然后,您将确保使用正确的频道名称。
此外,我加入了频道,并在没有.
标记的情况下收听事件,如下所示:
Echo.channel('laravel_database_testChannel').listen('EventClass', (e) => {
console.log(e);
});
一切正常。希望这可以节省遇到相同问题的时间。