- 安装 websocket 命令行客户端:
- 连接服务器(可通过
cookies.signed
和 request.authorization
进行认证):
-
wscat -c wss://echo.g-secret.com/cable -H 'Authorization:Token token=8A5A93D8-55EC-429E-9C66-B76CC74F23E5'
- 订阅频道:
- 发送:
{"command":"subscribe","identifier":"{\"channel\":\"NotificationsChannel\"}"}
- 返回:
-
{"identifier":"{\"channel\":\"NotificationsChannel\"}","type":"confirm_subscription"}
-
{"identifier":"{\"channel\":\"NotificationsChannel\"}","message":{"message":"当前连接数: 1"}}
- 发送消息:
- 发送:
{"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"}}
- 退订:
- 发送:
{"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