How to use a ruby Websocket client

1.4k views Asked by At

I'm trying to do my first app with a server-client Websocket on Ruby. I see a lot of codes like this one:

require 'eventmachine'
require 'em-websocket-client'

EM.run do
  conn = EventMachine::WebSocketClient.connect("ws://0.0.0.0:9110/message")

  conn.callback do
    data = {data: 'data'}
    conn.send_msg data.to_json
  end

  conn.errback do |e|
    puts "Got error: #{e}"
  end

  conn.stream do |msg|
    puts "<#{msg}>"
    conn.close_connection
 end

  conn.disconnect do
    puts "success"
    EM::stop_event_loop
  end
end

But I don't know how to use that code. Should I put all that inside a method in a class and replace "puts msg" with "return msg"? Or should I run the EM.run block as a daemon and "listen" the "puts"? I can't find examples about how to take the "msg" variable (the response from the server) out of the EM.run block.

Thanks for taking the time to read my question.

0

There are 0 answers