ios - 您将如何使用 ActionCable 订阅特定流
问题描述
我有一个本机 Rails Web 应用程序和一个具有聊天组件的 iOS 应用程序。我正在使用 ActionCable 提供实时消息传递。
在 MessageController 中创建消息时,服务器向 MessageChannel 中的两个流广播
- 呈现 html 以进行网络聊天
- 转到 iOS 应用程序的 json 对象
您可以创建特定于流的订阅吗?也就是在客户端,能不能从json广播中过滤掉html广播?
或者我应该创建一个 ApiMessageChannel 和一个 Web MessageChannel 吗?这感觉像是不必要的重复,因为创建将始终广播到 web 和 api。
消息频道
class MessageChannel < ApplicationCable::Channel
def subscribed
stop_all_streams
stream_for Group.find(params["id"])
stream_from "message:messages_api_#{params["id"]}"
end
end
消息控制器
def create
# ...
MessageChannel.broadcast_to group, message: render_to_string(message, locals: { previous_message: previous_message, type: group.type, current_user: current_user })
MessageChannel.broadcast_to "messages_api_#{group.id}", message: ApplicationController.render_with_signed_in_user(current_user, json: { sender: current_user.username, content: message.body })
end
聊天室控制器
import { Controller } from "stimulus"
import consumer from "channels/consumer"
export default class extends Controller {
static targets = [ "messages", "newMessage" ]
connect() {
this.subscription = consumer.subscriptions.create({ channel: "MessageChannel", id: this.data.get("id") }, {
connected: this._connected.bind(this),
disconnected: this._disconnected.bind(this),
received: this._received.bind(this)
})
}
disconnect() {
consumer.subscriptions.remove(this.subscription)
}
_connected() {
}
_disconnected() {
}
_received(data) {
if (data.message) {
this.messagesTarget.insertAdjacentHTML('beforeend', data.message);
$('.js-chat-messages').scrollTop($('.js-chat-messages')[0].scrollHeight);
}
}
clearMessage(event) {
this.newMessageTarget.value = ''
}
}
斯威夫特 iOS
static var ChannelIdentifier = "MessageChannel"
let actionCableClient = ActionCableClient(url: URL(string: "wss://localhost:3000/cable")!)
actionCableClient.headers = [
"Authorization": token,
"Accept": "application/json"
]
actionCableClient.connect()
let room_identifier = ["id" : "12"]
actionCableChannel = actionCableClient.create(ActionCableController.ChannelIdentifier, parameters: room_identifier, autoSubscribe: true, bufferActions: true )
actionCableChannel?.onReceive = { (data: Any?, error: Error?) in
print("recieved message!")
if let error = error {
print("ERROR: Unable to receive message from ActionCable Channel: \(error.localizedDescription)")
return
}
```
解决方案
要订阅特定的命名流,您可以:
class MessageChannel < ApplicationCable::Channel
def subscribed
# stream_from "message:messages_web"
# stream_from "message:messages_api"
# stream_from "message:messages_test"
stream_from "message:messages_#{params[:type]}"
# !! can also add in other parameters and add those on the client side for stream specific filtering
# stream_from "message:messages_#{params[:type]}_#{params[:id]}"
end
end
class MessagesController < ApplicationController
def create
MessageChannel.broadcast_to "messages_web", 'web'
MessageChannel.broadcast_to "messages_api", 'api'
MessageChannel.broadcast_to "messages_test", 'test'
end
end
import consumer from "channels/consumer"
this.subscription = consumer.subscriptions.create({ channel: "MessageChannel", type: 'web'}, {
connected: this._connected.bind(this),
disconnected: this._disconnected.bind(this),
received: this._received.bind(this)
})
这只会接收来自“message:messages_web”的消息
推荐阅读
- python - 使用 Python 打开文件时执行两个单独的“功能”的问题
- conda - 安装在 WSL2 上的 Miniconda3:未找到 conda 命令
- javascript - 谷歌地图:JS vs Android/Flutter
- ssrs-2008 - SSRS tablix 在分页符处显示额外的空白行
- python - 当它显示 int() 以 10 为底的无效文字时我该怎么办。我已经仔细检查了整个语法并且没有错误信息
- scheme - 如何在方案中编写一个函数,在带有汽车和 cdr 的列表中找到一个元素?
- c# - 由于 .Net 核心中的 CORS 策略,来自 Angular 的 http 请求被阻止
- javascript - 没有来自窗口的“targetcreated”。在 _blank 中打开文件下载
- python - Keras 密集算法的输入数据形状
- python - 如何为 .NET HTTP 服务器设置 Gitlab CI 并使用 Python 进行测试?