ruby-on-rails - Rails 5 actioncable 作为独立服务器

标签 ruby-on-rails sockets actioncable

没有太多关于 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) }

我连接成功了。我正在以

的形式收到 ping
MessageEvent {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/

相关文章:

linux:套接字编程,accept(sd, null, null)

c - send()和recv()给我带来问题

sockets - 为什么 bind() 和 accept() 让你指定结构的大小?

ruby-on-rails - 在Capybara-Webkit功能规范期间ActionCable无法连接

ruby-on-rails - 使用 Nitrous.io 和 Rails 配置 Sidekiq

jquery - 不要在 Ruby on Rails 6 中连接 Bootstrap 4 和 jQuery

mysql - Carrierwave 多次上传失败并显示 mount_uploaders

ruby-on-rails - Rspec:测试嵌套销毁操作

ruby-on-rails - Rails 可操作别名请求来源

ruby-on-rails - 未初始化常量 > ActionCable::Server::Configuration::ApplicationCable