Search code examples
ruby-on-railsrubyeventmachine

Setup concurrent web sockets with eventmachine


I want to use the websocket-eventmachine-client gem to try to create multiple concurrent web sockets but I'm not sure how to go about it.

Do I need to use EM.defer or something similar?

For instance, I have 20 URLs I need to connect and listen to. To connect to one I can do:

EM.run do
  ws = WebSocket::EventMachine::Client.connect(uri: host)

  ws.onopen do
    p :open
  end

  ws.onmessage do |msg, type|
    p [:message, msg]
  end

  ws.onclose do |code, reason|
    p :closed
  end

  ws.onerror do |error|
    p :error
  end
end

What's the code to do that 20 times? So far I've only managed to get connections in serial.


Solution

  • In the end I did:

    EM.run do
      EM::Iterator.new(connections_list, connections_list.size).each do |conn, iterator|
        # Connection stuff as in question
      end
    end