Action Cable 仅向客户端发送欢迎和 ping 消息

Action Cable only sending welcome and ping message to client

我可以让我的 Action Cable 正常工作,订阅也可以正常工作...

现在,我有一个简单的 HTML 页面,上面有一些 JS 用于连接和记录 WebSocket 消息。

这是我在 HTML 页面上使用的脚本(现在用于测试)

    var socket = new WebSocket('ws://localhost:3000/cable');
    socket.onopen = function(e) {
        console.log("Connection established")
    }
    socket.onclose = function(e) {
        console.log("Error occurred.");
        clients.Remove(socket)  
    }
    socket.onmessage = function(e){
        var server_message = e;
        console.log(server_message);
    }

    JSON.stringify(
        {
            "command": "message",
            "identifier": JSON.stringify({"channel": "tv_channel_1e80f418-08b0-478a-a77c-67a052934433" }),
            "data": {
                "action": "start_broadcasting"
            }
         }  
    ) 

我的 rails 输出已确认订阅存在,我的页面是控制台记录 ping 消息和来自 websocket 的欢迎消息。

如果我尝试广播任何东西,即使是作为测试(通过控制台或其他方式)

ActionCable.server.broadcast "tv_channel_1e80f418-08b0-478a-a77c-67a052934433", {message: "oh hai"}

它没有被客户捡到...

我已经通过 brew 安装了所有的 Redis,并在我的 cable.yml 文件中安装了以下内容

development: &development
  adapter: redis
  url: redis://localhost:6379

test:
  adapter: redis
  url: redis://localhost:6379

production:
  adapter: redis
  url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
  channel_prefix: can-i-haz-dashboard-server_production

我可以通过 redis-cli 确认消息正在传递到 redis 数据库。

我能找到的唯一答案涉及安装 redis。

我的 connection.rb 文件(频道编码用于测试)

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_channel

    def connect
      self.current_channel = ::Channel.find("1e80f418-08b0-478a-a77c-67a052934433")
    end

    private
      def find_channel

      end
  end
end

我的TvChannel.rb

class TvChannel < ApplicationCable::Channel
  def subscribed
    # stream_from "some_channel"
    stream_from "tv_channel_#{current_channel.id}"
    ActionCable.server.broadcast "tv_channel_#{current_channel.id}", 'Test message'
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def start_broadcasting
    "hello"
  end

end

我希望我做错的很简单。任何帮助将不胜感激。


编辑:抱歉,不确定我是否足够清楚。我的 Rails 应用 API 仅适用于 websocket,没有我为其提供服务的视图。 HTML 页面是独立的,不在 Rails 环境中。

太棒了,我希望如果不出意外,这对其他人有帮助。

我需要实际发送订阅字符串。

    socket.onopen = function(e) {
        console.log("Connection established")
        socket.send(subscribeString)
    }

    subscribeString = JSON.stringify(
        {
            "command": "subscribe",
            "identifier": JSON.stringify(
                {"channel": "channels:1e80f418-08b0-478a-a77c-67a052934433" }
                 )
        }  
    )