如何使用React连接到Laravel Websocket?

Sal*_*man 5 websocket laravel pusher reactjs react-native

我建立一个排序的应用程序,在那里我做后端与Laravel和与这两个前端ReactJSReact Native

每当客户发布订单和更新订单时,我都希望实时更新。

目前,我设法通过devmarketer他的教程使用pusher API运行websocket 。

我已经成功地在控制台中回显了命令,但是现在我想channel使用我的react应用程序进行访问

而在这一步,我正面临困难。

由于我不确定如何创建route适用于我的应用程序的以及如何通过此途径访问通道。

laravel官方文档提供了一个示例,说明如何访问pusher,但不提供如何通过外部连接(例如:我的本机应用程序)连接到pusher

window.Echo = new Echo({
  broadcaster: 'pusher',
  key: 'rapio1',
  host: 'http://backend.rapio',
  authEndpoint: 'http://backend.rapio/broadcasting/auth',
  auth: {
    headers: {
      // Authorization: `Bearer ${token}`,
      Accept: 'application/json',
    },
  }
  // encrypted: true
});
window.Echo.channel('rapio.1').listen('OrderPushed', (e) =>{
    console.log(e.order)
})
Run Code Online (Sandbox Code Playgroud)

所以我的问题是如何在我的React应用程序上访问广播频道?

新增后端事件


class OrderPushed implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $neworder;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Order $neworder)
    {
        $this->neworder = $neworder;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        //return new Channel('Rapio.'.$this->neworder->id);
       return new Channel('Rapio');

    }
    public function broadcastWith()
    {
        return [
            'status' => $this->neworder->status,
            'user' => $this->neworder->user->id,
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

您使用的是broadcastAs()后端的方法吗?

为了正确回答你的问题,了解这一点很重要,因为如果你是,Laravel echo 客户端会假设名称空间是 App\OrderPushed。

使用时,broadcastAs()您需要在它前面加上一个点前缀,以告诉echo不要使用命名空间,因此在您的示例中,它将是:

.listen('.OrderPushed')

此外,您不需要在后端进行任何额外的设置,以便每个客户端应用程序连接到套接字服务器,除非您希望进行多租户设置,使不同的后端应用程序能够使用 WebSockets 服务器。

我还使用wsHostandwsPort而不仅仅是主机和端口,但不确定这是否有区别