class SPSSub
Public Class Methods
new(hosts: [], port: '59000', host: nil, address: nil, callback: nil, log: nil )
click to toggle source
# File lib/sps-sub.rb, line 10 def initialize(hosts: [], port: '59000', host: nil, address: nil, callback: nil, log: nil ) log.info 'SPSSub/initialize: active' if log if host.nil? and address.nil? and hosts.any? then hostx, portx = hosts.first.split(':',2) portx ||= port @host, @port = hostx, portx else @host = host || address || 'localhost' @port = port.to_s end @callback = callback @retry_interval = 1 @hosts = hosts @log = log # Trap ^C Signal.trap("INT") { puts ' ... Bye' @status = :quit exit } # Trap `Kill ` Signal.trap("TERM") { @status = :quit exit } end
Public Instance Methods
em_connect(topic, &blk)
click to toggle source
# File lib/sps-sub.rb, line 59 def em_connect(topic, &blk) client = self host, port, log = @host, @port, @log EM.run do address = host + ':' + port @ws = ws = WebSocket::EventMachine::Client.connect(:uri => 'ws://' + address) ws.onopen do status_msg = "Connected" puts status_msg log.info 'SPSSub/em_connect: onopen: ' + status_msg if log end ws.onmessage do |fqm, type| topic, msg = fqm.split(/:\s/,2) EM.defer do if block_given? then blk.call(msg.to_s, topic.to_s) elsif @callback @callback.ontopic(topic, msg) else onmessage msg ontopic topic, msg end end end ws.onclose do status_msg = "Disconnected" log.info 'SPSSub/em_connect: onclose: ' + status_msg if log return if @status == :quit if @hosts.any? then hostx, portx = @hosts.rotate!.first.split(':',2) portx ||= @port @host, @port = hostx, portx client.em_connect topic else @retry_interval *= 2 sleep @retry_interval @retry_interval = 1 if @retry_interval > 30 status_msg = "retrying to connect to #{@host}:#{@port}... " puts status_msg log.info 'SPSSub/em_connect: onclose' + status_msg if log client.em_connect topic end end ws.onerror do |error| status_msg = "Error occured: #{error}" puts status_msg log.info 'SPSSub/em_connect: onerror: ' + status_msg if log end EventMachine.next_tick do ws.send 'subscribe to topic: ' + topic end end end
notice(s)
click to toggle source
# File lib/sps-sub.rb, line 44 def notice(s) EventMachine.next_tick do @ws.send s end end
onmessage(msg)
click to toggle source
This method is called when a new message is received
# File lib/sps-sub.rb, line 136 def onmessage(msg) puts "Received message: #{msg}" end
ontopic(topic, msg)
click to toggle source
Same as onmessage but includes the topic as well as the msg
# File lib/sps-sub.rb, line 142 def ontopic(topic, msg) end
subscribe(topic: '
click to toggle source
# File lib/sps-sub.rb, line 52 def subscribe(topic: '#', &blk) @t = Time.now em_connect(topic, &blk) end