Rails 5 – ActionCable – 无法升级到WebSocket

我试图在我的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应用程序,只是为了testing:

 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客户端上侦听的频道。 这也是有帮助的

编辑1 – 试图添加以下内容到development.rb

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

编辑2 – 也尝试添加像这样的节点客户端上的通道:

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

但是这两种尝试都没有奏效。

编辑3 – 另一个客户端testing:

  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'] 

为了发展,我只是使用正则expression式来允许所有的起源:

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

另外为了更容易地testing连接,使用这个jsfiddle – 现在消除了你的客户端的设置,只是想办法连接:

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

一旦你连接,我build议使用这个库来订阅你的客户端的动作有线电video道,我假设你会提到自从你提到Node

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