我想创建一个轨道ActionCable
之间的连接,它将作为Server
和NodeJs
作为Client
。与NodeJs(客户端)的Rails ActionCable连接(服务器)
这是我的代码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
这是的NodeJS代码server.js
文件
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}
和导轨服务器上显示以下日志
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
将使得Websocket连接上轨道ActionCable
并订阅SocketConnect
频道并将transmit
数据通过此通道导入Rails服务器。
我发现了chat
应用程序在rails动作服务器上的一些例子,其中client
和server
都在smae rails
平台上。但是,我还没有找到任何示例,其中client
与服务器位于不同的平台上。
但是,我无法找到此通道的Subscribe
的任何方法,并在两端建立稳定连接来传输数据,我也不知道如何从此请求获取数据。
请帮我这个。在此先感谢
感谢您的回复。当我将这些代码写入单独的'node.js'文件并使用 'node node.js'命令运行服务器时,它显示出以下错误。 '(函数(exports,require,module,__filename,__dirname){window.App = {}' 'ReferenceError:window is not defined' –
window is not necessary。Just do it =>“var App = { };“ –
声明'var App = {}之后;'我仍然收到错误'window is not defined'. 我假设它与'HTML' /'DOM'对象有关,但我只用js文件来运行'server'。我不知道如何初始化'window'。 –