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.
- #notice(s) ⇒ Object
-
#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 30 |
# 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 @retry_interval = 1 # 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
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 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/sps-sub.rb', line 47 def em_connect(topic, &blk) client = self host, port = @host, @port EM.run do address = host + ':' + port @ws = 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 @retry_interval *= 2 sleep @retry_interval @retry_interval = 1 if @retry_interval > 30 puts "retrying to connect to #{@host}:#{@port}... " 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 |
#notice(s) ⇒ Object
32 33 34 35 36 37 38 |
# File 'lib/sps-sub.rb', line 32 def notice(s) EventMachine.next_tick do @ws.send s end end |
#onmessage(msg) ⇒ Object
This method is called when a new message is received
107 108 109 |
# File 'lib/sps-sub.rb', line 107 def (msg) puts "Received message: #{msg}" end |
#ontopic(topic, msg) ⇒ Object
Same as onmessage but includes the topic as well as the msg
113 114 115 |
# File 'lib/sps-sub.rb', line 113 def ontopic(topic, msg) end |
#subscribe(topic: '#', &blk) ⇒ Object
40 41 42 43 44 45 |
# File 'lib/sps-sub.rb', line 40 def subscribe(topic: '#', &blk) @t = Time.now em_connect(topic, &blk) end |