4

I'm using eventmachine to read from a HornetQ topic, push to a Channel which is subscribed to by EM websocket connections. I need to prevent the @topic.receive loop from blocking, so have created a proc and am calling EventMachine.defer with no callback. This will run indefinitely. This works fine. I could also have just used Thread.new.

My question is, is this the correct way to read from a stream/queue and pass the data to the channel and is there a better/any other way to do this?

require 'em-websocket'
require 'torquebox-messaging'

class WebsocketServer

  def initialize
    @channel = EM::Channel.new

    @topic = TorqueBox::Messaging::Topic.new('/topics/mytopic')
  end 

  def start
    EventMachine.run do

      topic_to_channel = proc do
        while true
          msg = @topic.receive
          @channel.push msg
        end
      end

      EventMachine.defer(topic_to_channel)

      EventMachine::WebSocket.start(:host => "127.0.0.1", :port => 8081, :debug => false) do |connection|
        connection.onopen do

          sid = @channel.subscribe { |msg| connection.send msg }

          connection.onclose do            
            @channel.unsubscribe(sid)
          end
        end
      end                  
    end
  end
end

WebsocketServer.new.start
Barry Jordan
  • 2,666
  • 2
  • 22
  • 24

1 Answers1

1

This is ok, but EM.defer will spawn 20 threads, so I would avoid it for your use case. In general I would avoid EM entirely, especially the Java reactor as we never finished it.

The Torquebox has a native stomp over websockets solution that would be a much better way to go in this context, and solves a bunch of other encapsulation challenges for you.

If you really want to stick with EM for this, then I'd use Thread.new instead of defer, so as to avoid having 19 idle threads taking up extra ram for no reason.

raggi
  • 1,290
  • 9
  • 12