分享 ActionCable 的简易测试

mimosa · 2016年12月26日 · 2114 次阅读

  1. 安装 websocket 命令行客户端:
    • npm install -g wscat
  2. 连接服务器(可通过 cookies.signedrequest.authorization 进行认证):
    • wscat -c wss://echo.g-secret.com/cable -H 'Authorization:Token token=8A5A93D8-55EC-429E-9C66-B76CC74F23E5'
  3. 订阅频道:
    • 发送:{"command":"subscribe","identifier":"{\"channel\":\"NotificationsChannel\"}"}
    • 返回:
      • {"identifier":"{\"channel\":\"NotificationsChannel\"}","type":"confirm_subscription"}
      • {"identifier":"{\"channel\":\"NotificationsChannel\"}","message":{"message":"当前连接数: 1"}}
  4. 发送消息:
    • 发送:{"command":"message","identifier":"{\"channel\":\"NotificationsChannel\"}","data":"{\"message\":\"你好~~\",\"action\":\"speak\"}"}
      • 返回: {"identifier":"{\"channel\":\"NotificationsChannel\"}","message":{"message":"你好~~","action":"speak"}}
    • 发送:{"command":"message","identifier":"{\"channel\":\"NotificationsChannel\"}","data":"{\"action\":\"count\"}"}
      • 返回:{"identifier":"{\"channel\":\"NotificationsChannel\"}","message":{"message":"当前连接数: 1"}}
  5. 退订:
    • 发送:{"command":"unsubscribe","identifier":"{\"channel\":\"NotificationsChannel\"}"}
      • 什么也不会返回
# -*- 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)
  end

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

  private
    def channel_id
      "notifications:#{self.user_id || 'public'}"
    end
end
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号