【发布时间】:2017-03-13 17:30:09
【问题描述】:
我正在尝试在我的 Rails 5 应用程序上实现 webSocket。
这是我的频道:
class MessagesChannel < ApplicationCable::Channel
def subscribed
stream_from "messages_#{params[:topic]}"
end
end
在我的控制器中我这样做:
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 客户端上指定要收听的频道。这也很有帮助
EDIT 1 - 尝试将以下内容添加到 development.rb
config.action_cable.allowed_request_origins = ['http://localhost:3000']
EDIT 2 - 还尝试在节点客户端上添加通道,如下所示:
const ws = new WebSocket('ws://localhost:3000/cable', `messages_${topic}`);
但是两次尝试都没有成功。
EDIT 3 - 另一个客户端测试:
ws.on('open', function open() {
console.log("on open!!");
ws.send('{"command":"subscribe","identifier":"{\"channel\":\"MessagesChannel\"}"');
});
【问题讨论】:
标签: ruby-on-rails node.js websocket ruby-on-rails-5