我试图在我的Rails 5应用程序上实现webSocket。Rails 5 - ActionCable - 无法升级到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']
编辑2 - 还试图像这样节点客户端上添加频道:
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\"}"');
});
什么一个真棒答案被写入订阅行动有线频道!所以我测试过了。我已连接。有用。但是有一个问题。我正在使用nodejs来测试它。但我会有另一个客户端使用react-native(并使用WebSockets)。那么,我怎样才能使用websockets'订阅'频道?或者我必须使用另一个库来实现这一目标? –
另一个说明:https://github.com/mwalsher/actioncable-js/blob/master/dist/action_cable.js使用文档。而我的节点应用程序不会在浏览器上运行。 :( –