本文介绍了Rails ActionCable 连接(服务器)与 NodeJs(客户端)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a connection between rails ActionCable which will act as Server and NodeJs as Client.

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

This is my code in connection.rb file.

 # 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代码

And this is NodeJs code in server.js file

   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 服务器上显示以下日志

and on rails server displays the following logs

     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 频道并将 传输数据通过这个通道到Rails服务器.

What I want to achieve is that node server will make the Websocket connection on rails ActionCable and subscribe to SocketConnect Channel and will transmit the data to Rails server via this channel.

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

I have found some examples of chat application on rails action server where the client and server both are on smae rails platform. But, I haven't found any example where client is on separate palatform than server.

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

But, I am unable to find any method to Subscribe for this channel and make a stable connection on both ends to transmit data and I also don't know how to get data from this request.

请帮我解决这个问题.提前致谢

Please help me in this. Thanks in advance

推荐答案

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

Try this. Sending subscribe and setting identifier for socketchannel is important point.

# 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 也有助于你.

这篇关于Rails ActionCable 连接(服务器)与 NodeJs(客户端)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:27