Laravel Echo与Pusher不在私人频道上接收消息

时间:2019-12-23 03:09:43

标签: php laravel sockets pusher laravel-echo

每次我切换到专用频道时,浏览器都不会收到任何消息,但是仅使用标准频道时,它会起作用。我当前的设置包括一个用于前端的Vue CLI应用程序和一个使用Laravel Passport进行身份验证的Laravel API作为后端的

这是用于连接Pusher的代码。

import LaravelEcho from 'laravel-echo';

// ...

export const Echo = new LaravelEcho({
  broadcaster: 'pusher',
  key: pusherKey,
  cluster,
  encrypted: true,
});

Echo.connector.pusher.config.authEndpoint = `${baseURL}/broadcasting/auth`;

store.watch((state: any) => state.$auth.token, (token: string) => {
  Echo.connector.pusher.config.auth.headers['Authorization'] = `Bearer ${token}`;
});

store.watch((state: any) => state.$auth.user, (n: any, o: any) => {
  if (n) {
    console.log(`App.User.${n.id}`); // This is being logged to the console App.User.1
    Echo.private(`App.User.${n.id}`)
      .listen('.friend.request', (e: any) => {
        console.log({ e });
      });
  }
});

这是频道路由文件:

<?php

Broadcast::channel('App.User.{id}', function ($user, $id) {
    return true;
    // return (int) $user->id === (int) $id;
});

事件的简化版本。

<?php

namespace App\Events;

// ...

class FriendRequestSent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    // ...

    public function broadcastOn()
    {
        return new PrivateChannel("App.User.{$this->friend->id}");
    }

    // ...
}

我已经设置了此测试路线:

<?php

Route::get('/', function (Request $request) {
    event(new FriendRequestSent(User::find(1), User::find(1)));
});

运行Echo.private()...代码后,我可以在Pusher仪表板中看到以下内容:

Pusher Dashboard Connected

然后从/路由触发事件后:

Queue

最后,Pusher接了事件,控制台中什么也没显示:

Output

但是,如果我将new PrivateChannel(...)更改为new Channel(...),然后使用Echo.channel而不是Echo.private,它将开始在控制台中显示某些内容。

有人知道为什么会这样吗?


对此进行了更新,我找到了此网页:Pusher Docs - Debugging

Pusher :  : ["Event sent",{"event":"pusher:subscribe","data":{"auth":"some_auth_code_returned_from_api_broadcasting_auth","channel":"private-App.User.1"}}]

Pusher :  : ["Event recd",{"event":"pusher_internal:subscription_succeeded","channel":"private-App.User.1","data":{}}]

Pusher :  : ["No callbacks on private-App.User.1 for pusher:subscription_succeeded"]

我可以看到最终输出No callbacks on private-App.User.1...可能是导致问题的原因,但我唯一能发现的是:

  1. 更改为BROADCAST_DRIVER=pusher
  2. 尝试在channels.php中使用此代码:
<?php

// Notice {userId} rather than {id}.
Broadcast::channel('App.User.{userId}', function ($user, $userId) {
    return (int) $user->id === (int) $userId;
});

我现在已经使用Socket.IO尝试了此操作,并且得到了相同的结果:

Socket.IO控制台输出:

[6:36:11 AM] - Preparing authentication request to: http://isapi.test
[6:36:11 AM] - Sending auth request to: http://isapi.test/api/broadcasting/auth
[6:36:12 AM] - gT9--_C_2c-KwoxLAAAE authenticated for: private-App.User.1
[6:36:12 AM] - gT9--_C_2c-KwoxLAAAE joined channel: private-App.User.1

我的Socket.IO配置:

import io from 'socket.io-client';

(window as any).io = io;

export const Echo = new LaravelEcho({
  broadcaster: 'socket.io',
  host: `${baseURL.substr(0, baseURL.length - 4)}:6001`,
  encrypted: true,
});

Echo.connector.socket.io.opts.authEndpoint = `${baseURL}/broadcasting/auth`;

store.watch(
  (state: any) => state.$auth.token,
  (token: string) => {
    Echo.connector.socket.io.opts.auth.headers.Authorization = `Bearer ${token}`;
  },
);

因此,我创建了具有以下依赖关系的Vue和Laravel的全新安装:

Laravel:

  • 护照
  • Barry CORS
  • 推送服务器

Vue:

  • TypeScript安装
  • 我的自定义HTTP包装器(仅包装fetch和axios)

它起作用了,所以我只需要找出我做过的不同事情,看看我是否可以那样解决。如果您想查看此测试代码,我已将其放置在此存储库中。

https://github.com/kingga/stackoverflow-59449785

1 个答案:

答案 0 :(得分:0)

与往常一样,这是一个非常简单的解决方案,但却被忽略了。

我有两个store.watch。一个关于令牌,另一个关于用户。用户必须先运行,然后再运行令牌,从而导致在连接到专用通道时未设置令牌。例如

store.watch(
  (state: any) => state.$auth.token,
  (token: string) => {
    Echo.connector.pusher.config.auth.headers.Authorization = `Bearer ${token}`;
  },
);

store.watch(
  (state: any) => state.$auth.user,
  (n: any, o: any) => {
    if (n) {
      // Added this line to fix the issue.
      Echo.connector.pusher.config.auth.headers.Authorization = `Bearer ${store.state.$auth.token}`;
      Echo.private(`App.User.${n.id}`).listen(
        '.friend.request',
        (data: any) => {
          // store.state.$friends.requests = data;
          console.log({ data });
        },
      );
    } else if (o) {
      Echo.private(`App.User.${o.id}`)
        .stopListening('.friend.request');
    }
  },
);