Class: EZMQ::Subscriber

Inherits:
Socket
  • Object
show all
Defined in:
lib/ezmq.rb

Overview

Subscribe socket that listens for messages with an optional topic.

Instance Attribute Summary (collapse)

Attributes inherited from Socket

#context, #decode, #encode, #socket

Instance Method Summary (collapse)

Methods inherited from Socket

#bind, #connect, #receive, #send

Constructor Details

- (Publisher) initialize(**options)

Note:

The default behaviour is to output and messages received to STDOUT.

Creates a new Subscriber socket.

Parameters:

  • options (Hash)

    optional parameters.

Options Hash (**options):

  • topic (String)

    a topic to subscribe to.

See Also:



218
219
220
221
# File 'lib/ezmq.rb', line 218

def initialize(**options)
  super :connect, ZMQ::SUB, options
  subscribe options[:topic] if options[:topic]
end

Instance Attribute Details

- (Object) action

Returns the value of attribute action



206
207
208
# File 'lib/ezmq.rb', line 206

def action
  @action
end

Instance Method Details

- (void) listen {|message| ... }

This method returns an undefined value.

By default, waits for a message and prints it to STDOUT.

Yields:

  • message passes the message received to the block.

Yield Parameters:

  • message (String)

    the message received.



256
257
258
259
260
261
262
263
264
# File 'lib/ezmq.rb', line 256

def listen
  loop do
    if block_given?
      yield receive
    else
      puts receive
    end
  end
end

- (Boolean) subscribe(topic)

Note:

By default, a Subscriber filters all incoming messages. Without

Establishes a new message filter on the socket.

calling subscribe at least once, no messages will be accepted. If topic was provided, #initialize calls #subscribe automatically.

prefix will be accepted.

Parameters:

  • topic (String)

    a topic to subscribe to. Messages matching this

Returns:

  • (Boolean)

    was subscription successful?



234
235
236
# File 'lib/ezmq.rb', line 234

def subscribe(topic)
  @socket.setsockopt(ZMQ::SUBSCRIBE, topic) == 0
end

- (Boolean) unsubscribe(topic)

Removes a message filter (as set with subscribe) from the socket.

Parameters:

  • topic (String)

    the topic to unsubscribe from. If multiple filters with the same topic are set, this will only remove one.

Returns:

  • (Boolean)

    was unsubscription successful?



245
246
247
# File 'lib/ezmq.rb', line 245

def unsubscribe(topic)
  @socket.setsockopt(ZMQ::UNSUBSCRIBE, topic) == 0
end