【发布时间】:2020-03-11 14:18:53
【问题描述】:
我创建了一个项目,其中有一个客户和另一个承包商。我在 Rails actioncable 上实现了 ruby 用于聊天。一切都很好,但是当两个不同的人与一个人聊天时,问题就来了,那个人正在套接字窗口中接收两条消息。我意识到我已经将conversation-#{user_id} 设置为一个频道,所以用户正在这个频道上收听现在两个人向他发送聊天,他们都会来到同一个频道。我怎样才能避免这种情况?或者我可以在频道字符串中添加另一个用户,但我发现这非常困难。任何想法我必须将参数发送到订阅方法。
连接
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_session_user
end
def find_session_user
current_user = User.find_by(id: cookies.signed[:actioncable_user_id])
current_user || reject_unauthorized_connection
end
end
我的对话频道
class ConversationChannel < ApplicationCable::Channel
def subscribed
stream_from "conversations-#{current_user.id}"
end
def unsubscribed
stop_all_streams
end
def speak(data)
message_params = data["message"].each_with_object({}) do |el, hash|
hash[el.values.first] = el.values.last
end
end
ActionCable.server.broadcast(
"conversations-#{current_user.id}",
message: message_params,
)
end
此代码只是精简版,但由于它将conversation-user_id作为通道启动,所以当它连接并且其他人发送消息时,该用户将在同一个套接字中接收它们。所以我必须像`conversation-user_id-anotehr_user。现在它正在网络/移动设备上运行,一切都很好,但是当两个用户与一个用户通信时,它会通过在一个套接字上显示两个用户聊天来产生问题。
知道如何创建这样的频道。
【问题讨论】:
标签: ruby-on-rails websocket actioncable