【问题标题】:ActionCable never establishes connection to channelActionCable 从不与通道建立连接
【发布时间】:2017-11-20 00:37:14
【问题描述】:

我正在尝试运行第一个 ActionCable 示例,但是,我觉得从来没有建立从客户端到通道的连接。在此处未提及的所有其他内容上,我几乎都遵循了edge guides

# app/channels/notifications_channel.rb
class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    byebug
    stream_from "notifications"
  end

  def unsubscribed
    stop_all_streams
  end

  def receive(data)
    ActionCable.server.broadcast("notifications", data)
  end
end

byebug 从未被调用过。实际上,我可以将一堆语法乱码放入该文件中,并且不会在任何地方看到错误。就像文件永远不会加载一样。

这里是 javascript,如果它会建立连接,我希望看到“已连接”警报,但这种情况永远不会发生。该文件已加载并正确执行,因为我可以在浏览器控制台中检查 App 变量,它会将 App.notifications 显示为有效的订阅对象(尽管大多数属性都是函数,但它对调试没有帮助)。

// app/assets/javascripts/channels/notifications.js
App.notifications = App.cable.subscriptions.create("NotificationsChannel", {
  connected: function() {
    // Called when the subscription is ready for use on the server
    alert('connected');
  },

  disconnected: function() {
    // Called when the subscription has been terminated by the server
  },

  received: function(data) {
    alert(data)
    // Called when there's incoming data on the websocket for this channel
    $("#notifications").prepend(data.html);
  }
});

如果它有任何帮助,我的 Puma 总是以“单一模式”启动,我不确定这是否可能是问题,也不知道如何解决它。

【问题讨论】:

    标签: ruby-on-rails websocket real-time puma actioncable


    【解决方案1】:

    所以这就是原因。我不知何故只是试图将所有内容设置为默认值,看看它是否会起作用,并且确实如此。然后,我通过慢慢添加配置和代码来找出问题所在,即config/environments/development.rb 中的以下行:

    config.reload_classes_only_on_change = false
    

    将此设置为true 解决了它。

    【讨论】:

    • 谢谢!我遇到了同样的问题,改成reload_classes_only_on_change就解决了!
    【解决方案2】:

    我遇到了同样的问题,设置 config.reload_classes_only_on_change 没有帮助。

    我需要用turbolinks:load包装频道代码

    $(document).on("turbolinks:load", function() {
       // ...
       const channel = consumer.subscriptions.create(
         { channel: channel_name, ...other params },
         connected() {}, 
         disconnected() {}
       )
    })
    

    【讨论】:

      猜你喜欢
      • 2013-11-08
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 2022-12-22
      • 2022-07-23
      • 2018-11-15
      • 2019-09-07
      • 2011-03-04
      相关资源
      最近更新 更多