新手问题 你好,在使用 ActionCable,如果掉线后重连,怎么让 Rails 服务端重现推送错过的信息

jimmygui · 2016年11月01日 · 最后由 hz_qiuyuanxin 回复于 2016年11月02日 · 2219 次阅读

我按官方实例写聊天室,然后想实现掉线重连后获取错过的数据,是不是只能刷新页面,有没有不刷新而是重新推送错过的信息。

短线重连得在客户端做,类似 timer,不错过消息可以持久化消息,简单 mark read or unread.

这需要一种建立一种机制,客户端收到消息后回执,标注过的消息从队列中删除,客户端上线(subscribed)后触发(未标示)队列。😱

# -*- encoding: utf-8 -*-

class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stop_all_streams
    stream_from channel_id
    count # 连接后可触发
  end

  def unsubscribed
    stop_all_streams
  end

  def speak(data)
    ActionCableWorker.perform_async(channel_id, data) # Sidekiq 任务
  end

  def count
    speak( message: "当前连接数: #{ActionCable.server.connections.count}" )
  end

  private
    def channel_id
      "notifications:#{self.user_id || 'public'}"
    end
end

坐等答案,我也在玩 ActionCable

ActionCable 前端部分已经自己实现了断线重连。楼主的这个问题属于业务范畴,这需要你自己去构建一套机制来保证客户端能够收到所有它未拿到的消息,2 楼 3 楼都提供了思路。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号