gpt4 book ai didi

ruby-on-rails - Rails 5 - ActionCable - 无法升级到 WebSocket

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:58 25 4
gpt4 key购买 nike

我正在尝试在我的 Rails 5 应用程序上实现 webSocket。

这是我的 channel :

class MessagesChannel < ApplicationCable::Channel
def subscribed
stream_from "messages_#{params[:topic]}"
end
end

在我的 Controller 中我这样做:

    ActionCable.server.broadcast "messages_#{params[:topic_id]}",
message: @message.message,
user: current_user.name

还有我的连接类(也使用设备):

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

def connect
self.current_user = find_verified_user
logger.add_tags 'ActionCable', current_user.email
end

protected

def find_verified_user # this checks whether a user is authenticated with devise
if verified_user = env['warden'].user
verified_user
else
reject_unauthorized_connection
end
end
end
end

客户端是一个Nodejs应用程序,只是为了测试:

module.exports.webSocket = function(topic){
const WebSocket = require('ws');

const ws = new WebSocket('ws://localhost:3000/cable');

ws.on('open', function open() {
console.log("on open!!");
});

ws.on('message', function incoming(data, flags) {
console.log("got here!");
console.log(data);
console.log(flags);
// flags.binary will be set if a binary data is received.
// flags.masked will be set if the data was masked.
});
};

这就是我得到的:

Started GET "/cable" for 127.0.0.1 at 2017-03-13 14:25:01 -0300
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2017-03-13 14:25:01 -0300
Request origin not allowed:
Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
Finished "/cable/" [WebSocket] for 127.0.0.1 at 2017-03-13 14:25:01 -0300

我也不知道如何指定NodeJS客户端监听的 channel 。这也会有帮助

编辑1 - 尝试将以下内容添加到development.rb

config.action_cable.allowed_request_origins = ['http://localhost:3000']

编辑 2 - 还尝试在 Node 客户端上添加 channel ,如下所示:

const ws = new WebSocket('ws://localhost:3000/cable', `messages_${topic}`);

但是两次尝试都没有成功。

编辑 3 - 另一个客户端测试:

  ws.on('open', function open() {
console.log("on open!!");
ws.send('{"command":"subscribe","identifier":"{\"channel\":\"MessagesChannel\"}"');
});

最佳答案

您的客户端在哪个端口上运行?您想要允许客户端,因此如果 Rails 在 localhost 3000 上运行,您需要将其更改为正确的原始 url:

config.action_cable.allowed_request_origins = ['http://localhost:3000']

为了开发,我暂时只使用正则表达式来允许所有来源:

config.action_cable.allowed_request_origins = [ /http:\/\/.*/, /https:\/\/.*/ ]

此外,为了更轻松地测试连接,请使用此 jsfiddle - 现在无需对客户端进行设置,只需计算出是否能够连接:

http://jsfiddle.net/BrilliantLa8s/bxkerzf8/2/

连接后,我建议使用此库从您的客户端订阅操作有线电视 channel ,因为您提到了 Node,我认为该库将用 JavaScript 编写

https://www.npmjs.com/package/actioncable-js

关于ruby-on-rails - Rails 5 - ActionCable - 无法升级到 WebSocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42769831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com