我将创建基于ActionCable处理WebSocket的Rails API (首先,在API模式下使用ActionCable是个好主意?)。ActionCable在全堆栈Rails应用程序中工作得很好,但我遇到了一些困难。第一个问题是哪种格式应该将所有请求都发送到actionCable服务器。到目前为止,我只发现了订阅操作:
{
"command":"subscribe",
"identifier":"{\"channel\":\"SomeChannel\"}"
}其他人呢?有没有什么文档可以让我找到它?
提前感谢
发布于 2017-06-21 16:07:37
对于包含非浏览器客户端的应用程序接口项目,我可能会避免使用ActionCable语义和内部协议。
例如:
这并不意味着您需要完全远离Rails。在非Rails Websocket中使用Rails模型和代码应该很容易。
此外,Ruby还为ActionCable提供了一些不错的Websocket替代方案。
我是有偏见的,作为Iodine - an HTTP/Websocket server with native Pub/Sub和Plezi.io, a real-time web application framework的作者...但我可能会使用碘(有或没有Plezi提供的额外舒适性)。
一个简单的带有Plezi的Websocket应用程序看起来像这样(说真的,使用irb从终端运行以下代码,它是有效的):
require 'plezi'
class ChatServer
def index
"Use Websockets to connect."
end
def on_open
@name = params['id'] || "anonymmous"
subscribe channel: "chat"
publish channel: "chat", message: "#{@name} joind the chat."
write "Welcome, #{@name}!"
end
def on_close
publish channel: "chat", message: "#{@name} left the chat."
end
def on_message data
publish channel: "chat", message: "#{@name}: #{data}"
end
def on_shutdown
write "Server shutting down. Goodbye #{@name}"
end
end
Plezi.route '/', ChatServer
# We'll monitor message just for kicks:
subscription = Iodine.subscribe(pattern: "*") do |channel, message|
# print a log?
puts "\n* Message on channel #{channel}:\n#{message}\n"
end
# make sure we don't duplicate our monitoring on every process.
root_pid = Process.pid
Iodine.run { Iodine.unsubscribe(subscription) unless Process.pid == root_pid }
exit不需要Redis服务器,也不需要准备特殊的东西,并且可以在Rails应用程序中使用plezi作为中间件(运行iodine服务器而不是puma)。
https://stackoverflow.com/questions/44663772
复制相似问题