没有太多关于 Action 电缆的文档,所以我对此有点迷茫。 我正在玩 rails 5 应用程序,我正在尝试将 rails5 应用程序用作纯粹的 api,并将我的 JS 托管在其他地方。所以当我启动我的 actioncable 服务器时,我可以很容易地连接到 websocket,只需使用我内置的浏览器套接字支持:
var socket = new WebSocket('localhost:3000/cable')
// and then do
socket.onmessage = function(data) { console.log(data) }
我连接成功了。我正在以
的形式收到 pingMessageEvent {isTrusted: true, data: "{"type":"ping","message":1462992407}", ... etc
除了我似乎无法向客户端广播任何消息。我试过:
ActionCable.server.broadcast('test',{ yes: true })
但只有 ping 进来。ActionCable 有它自己的概念,我还没有完全理解这些概念,比如 channel 和在 Rails 应用程序中“正常工作”的东西。但是我怎样才能使用 actioncable 的套接字服务器成功构建一个单独的独立 JS 应用程序呢?
最佳答案
我将 ActionCable 与 iOS 应用程序一起使用。一切正常。
ActionCable 使用发布/订阅模式。
Pub/Sub, or Publish-Subscribe, refers to a message queue paradigm whereby senders of information (publishers), send data to an abstract class of recipients (subscribers), without specifying individual recipients. Action Cable uses this approach to communicate between the server and many clients.
这意味着您应该先创建一个新 channel ,
rails g channel my_channel
然后在您的 channel 中发送一些测试消息:
# app/channels/my_channel.rb
class MyChannel < ApplicationCable::Channel
def subscribed
stream_from "my_channel"
ActionCable.server.broadcast "my_channel", 'Test message'
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
然后将以下内容发送到您的服务器:
{'command': 'subscribe', 'identifier': {\'channel\':\'MyChannel\'}}
作为返回,您将获得第一帧。
关于ruby-on-rails - Rails 5 actioncable 作为独立服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37171064/