【问题标题】:Rails ActionCable Connection(Server) with NodeJs(Client)Rails ActionCable 连接(服务器)与 NodeJs(客户端)
【发布时间】:2017-11-17 07:39:44
【问题描述】:

我想在 Rails ActionCable 之间创建一个连接,它将充当 ServerNodeJs 作为 Client

这是我在connection.rb 文件中的代码。

 # app/channels/application_cable/connection.rb
 module ApplicationCable
   class Connection < ActionCable::Connection::Base
    identified_by :uuid

    def connect
     self.uuid = SecureRandom.uuid
    end
  end
 end

这是我频道的代码。

 # app/channels/socket_connection_channel.rb
 class SocketConnectionChannel < ApplicationCable::Channel
  def subscribed
   stream_from "socket_connect"
  end

  def speak
    ActionCable.server.broadcast("socket_connect",
                             message: "Connected")
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
   end

 end

这是 server.js 文件中的 NodeJs 代码

   const WebSocket = require('ws');

   const ws = new WebSocket('ws://0.0.0.0:3001/cable');

   ws.on('open', function open() {
     ws.send(JSON.stringify({'data': 'Sample Data'}));
   });

    ws.on('message', function incoming(data) {
     console.log(data);
     });

   ws.on('socket_connected', function incoming(data) {
      console.log('socket');
    });

当我运行服务器时node server

  {"type":"welcome"}
  {"type":"ping","message":1497487145}
  {"type":"ping","message":1497487148}
  {"type":"ping","message":1497487151}

并且在 Rails 服务器上显示以下日志

     Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2017-06-15 
    02:39:02 +0200
      Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
      Registered connection (5db66385-0923-4633-8837-ba957fc0a7f5)
      Received unrecognized command in {"data"=>"Sample Data"}

我想要实现的是node server 将在rails ActionCable 上建立Websocket 连接并订阅SocketConnect 频道并将transmit 数据通过此频道发送到Rails 服务器。

我在 Rails 操作服务器上找到了一些 chat 应用程序示例,其中 clientserver 都位于 smae rails 平台上。但是,我还没有找到任何 client 位于与服务器不同的平台上的示例。

但是,我无法为这个通道找到Subscribe 的任何方法,并在两端建立稳定的连接来传输数据,我也不知道如何从这个请求中获取数据。

请帮助我。提前致谢

【问题讨论】:

    标签: ruby-on-rails node.js websocket client-server actioncable


    【解决方案1】:

    试试这个。为socketchannel发送订阅和设置标识符很重要。

    导轨

    # app/channels/socket_connection_channel.rb
     class SocketConnectionChannel < ApplicationCable::Channel
      def subscribed
       @uuid = params[:uuid]
       stop_all_streams
       stream_from "socket_connect_#{@uuid}"
       logger.info ">>> Subscribed #{@uuid}!"
      end
    
      def speak
        logger.info "[ActionCable] received message : #{data['message']}" 
        ActionCable.server.broadcast "socket_connect_#{@uuid}", message: "#{data['message']} from server"
      end
    
      def unsubscribed
        # Any cleanup needed when channel is unsubscribed
       end
    
     end
    

    node.js

    var App = {};
    
    App.sendmessage = function(send) {
      data = {
        message : send,
        action : "speak"
      };
      message = {
        command: "message",
        identifier: JSON.stringify(App.param),
        data: JSON.stringify(data)
      };    
      App.ws.send(JSON.stringify(message));
    }
    
    App.connect_server = function() {         
      const WebSocket = require('ws');
      App.ws = new WebSocket('ws://0.0.0.0:3001/cable', ["actioncable-v1-json", "actioncable-unsupported"]);
    
      App.param = {channel: "SocketConnectionChannel", uuid: guid()};
    
      App.ws.on('open', function open() {
        data = {
          command: "subscribe",
          identifier: JSON.stringify(App.param)
        }
        App.ws.send(JSON.stringify(data));
      });  
      App.ws.on('message', function (event) {
        console.log(event);
      });
      function guid() {
       function s4() {
         return Math.floor((1 + Math.random()) * 0x10000)
          .toString(16)
          .substring(1);
       }
       return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
        s4() + '-' + s4() + s4() + s4();
      }
    }
    App.connect_server();
    

    node.js

    App.sendmessage("Hello world");
    

    https://github.com/mwalsher/actioncable-js对你也有帮助。

    【讨论】:

    • 感谢您的回复。当我在单独的 node.js 文件中编写此代码并使用 node node.js 命令运行服务器时,它会显示以下错误。 (function (exports, require, module, __filename, __dirname) { window.App = {}ReferenceError: window is not defined
    • window 不是必需的。就这么做 => "var App = {};"
    • 在声明var App = {}; 后,我仍然收到错误window is not defined。我假设它与HTML/DOM 对象相关联。但我只使用 js 文件来运行server。我不知道如何初始化window
    • 谢谢。你真棒。有效 :) 。您能否分享任何参考或来源,其中提供了其他方法/功能的所有详细信息/用法。
    • 请参阅此stackoverflow.com/questions/35320791/…。会更有帮助。 :D
    猜你喜欢
    • 2014-04-06
    • 1970-01-01
    • 2020-02-13
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多