Skip to content

How to Subscribe to Messages

mkeen edited this page Apr 9, 2012 · 3 revisions

To create a stomp subscription, the required code is simple.

Noise::Connection.new do
  subscribe "/topic/my_topic"
end

However, there will be nothing to call when a message for the above subscription is received. So we'll need to add a callback for the subscription with either the on_message method, or the on method.

If you're familiar with STOMP, you know that there are a finite number of commands you will receive from the server. These commands are CONNECTED, MESSAGE, RECEIPT, and ERROR. Noise gives you the ability to subscribe to these commands. For example:

Noise::Connection.new do
  subscribe "/topic/my_topic"
  on "message", true do |frame|
    puts frame
  end

end

The above is limited in that it will always be called whenever any message arrives. How can we filter incoming messages? There is a special on_message method. Check it out:

Noise::Connection.new do
  subscribe "/topic/my_topic"
  on_message "/topic/my_topic", true do |frame|
    puts 'a message came in on "/topic/my_topic"'
  end

end

This subscription is to the "/topic/my_topic" destination only. It will not fire when messages come in for other destinations.

Clone this wiki locally