Simple WebSocket Client for Ruby. It can work with ActionCable server
gem install websocket-client-simple
require 'rubygems'
require 'websocket-client-simple'
require 'json'
ws = WebSocket::Client::Simple.connect 'ws://example.com:3000/cable'
ws.on :message do |msg|
puts msg.data
end
ws.on :open do
# Send command to subscribe to ActionCable's specific channel after connect to socket
ws.send ({"command":"subscribe","identifier":"{\"channel\":\"LocationChannel\",\"request_id\":\"b03e65bc-994c-d1e6-cd71-51b7a86242d8\"}"}.to_json)
end
ws.on :close do |e|
p e
exit 1
end
ws.on :error do |e|
p e
end
loop do
ws.send STDIN.gets.strip
end
connect
runs a given block before connecting websocket
WebSocket::Client::Simple.connect 'ws://example.com:8888' do |ws|
ws.on :open do
puts "connect!"
end
ws.on :message do |msg|
puts msg.data
end
end
There really isn't that much to this gem. :-)
- Connect to the Action Cable URL
- After the connection succeeds, send a subscribe message
- The subscribe message JSON should look like this
{"command":"subscribe","identifier":"{\"channel\":\"MeshRelayChannel\"}"}
- You should receive a message like this:
{"identifier"=>"{\"channel\":\"MeshRelayChannel\"}", "type"=>"confirm_subscription"}
- Once subscribed, you can send messages.
- Make sure that the
action
string matches the data-handling method name on your ActionCable server. - Your message JSON should look like this:
{"command":"message","identifier":"{\"channel\":\"MeshRelayChannel\"}","data":"{\"to\":\"user1\",\"message\":\"hello from user2\",\"action\":\"chat\"}"}
- Received messages should look about the same
- Notes:
- Every message sent to the server has a
command
andidentifier
key. - Ping messages from the action cable server look like:
{ "type" => "ping", "message" => 1461845503 }
- The channel value must match the
name
of the channel class on the ActionCable server. identifier
anddata
are redundantly jsonified. So, for example (in ruby):
payload = {
command: 'command text',
identifier: { channel: 'MeshRelayChannel' }.to_json,
data: { to: 'user', message: 'hi', action: 'chat' }.to_json
}.to_json
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request