我試圖在我的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使用文檔。而我的節點應用程序不會在瀏覽器上運行。 :( –