I want to create a connection between rails ActionCable
which will act as Server
and NodeJs
as Client
.
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
This is code of my channel.
# 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
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');
});
When I run the server node server
{"type":"welcome"}
{"type":"ping","message":1497487145}
{"type":"ping","message":1497487148}
{"type":"ping","message":1497487151}
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"}
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.
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.
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