Class: SPSSub
- Inherits:
-
Object
- Object
- SPSSub
- Defined in:
- lib/sps-sub.rb
Instance Method Summary collapse
- #em_connect(topic, &blk) ⇒ Object
-
#initialize(port: '59000', host: nil, address: nil, callback: nil) ⇒ SPSSub
constructor
A new instance of SPSSub.
-
#onmessage(msg) ⇒ Object
This method is called when a new message is received.
-
#ontopic(topic, msg) ⇒ Object
Same as onmessage but includes the topic as well as the msg.
- #subscribe(topic: '#', &blk) ⇒ Object
Constructor Details
#initialize(port: '59000', host: nil, address: nil, callback: nil) ⇒ SPSSub
Returns a new instance of SPSSub.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/sps-sub.rb', line 10 def initialize(port: '59000', host: nil, address: nil, callback: nil) @host = host || address || 'localhost' @port = port.to_s @callback = callback # Trap ^C Signal.trap("INT") { puts ' ... Bye' @status = :quit exit } # Trap `Kill ` Signal.trap("TERM") { @status = :quit exit } end |
Instance Method Details
#em_connect(topic, &blk) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
# File 'lib/sps-sub.rb', line 41 def em_connect(topic, &blk) client = self host, port = @host, @port EM.run do address = host + ':' + port ws = WebSocket::EventMachine::Client.connect(:uri => 'ws://' + address) ws.onopen do puts "Connected" end ws. do |fqm, type| topic, msg = fqm.split(/:\s/,2) EM.defer do if block_given? then blk.call(msg, topic) elsif @callback @callback.ontopic(topic, msg) else msg ontopic topic, msg end end end ws.onclose do puts "Disconnected" return if @status == :quit sleep 2 puts 'retrying to connect ... ' client.em_connect topic end ws.onerror do |error| puts "Error occured: #{error}" end EventMachine.next_tick do ws.send 'subscribe to topic: ' + topic end end end |
#onmessage(msg) ⇒ Object
This method is called when a new message is received
97 98 99 |
# File 'lib/sps-sub.rb', line 97 def (msg) puts "Received message: #{msg}" end |
#ontopic(topic, msg) ⇒ Object
Same as onmessage but includes the topic as well as the msg
103 104 105 |
# File 'lib/sps-sub.rb', line 103 def ontopic(topic, msg) end |
#subscribe(topic: '#', &blk) ⇒ Object
33 34 35 36 37 38 39 |
# File 'lib/sps-sub.rb', line 33 def subscribe(topic: '#', &blk) @t = Time.now em_connect(topic, &blk) end |