【发布时间】:2019-12-10 17:00:03
【问题描述】:
我可以让我的 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 db。
我能找到的唯一答案是安装 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
我的电视频道.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 应用程序是仅用于 websocket 的 API,我没有为它服务的视图。 HTML 页面是独立的,不在 Rails 环境中。
【问题讨论】:
-
这个js在哪里写的?我的意思是在哪个文件中?
-
嗨 @Vishal 感谢您的回复。它在一个单独的仓库中,它是一个独立的 html 文件
-
动作线的流程完全不同。观看此视频youtube.com/watch?v=n0WUjGkDFS0。您不应该在 html 文件中编写套接字的此功能。
-
嗨 @Vishal 我使用 HTML 文件订阅和使用来自 Web 套接字的数据,而不是实现它。
-
很高兴你发现它解决了。
标签: javascript ruby-on-rails websocket redis actioncable