Sha256: 30a5c78529de5a82d7d96e75f863f790de6948d3d7f90ce25158d15e409b9ceb

Contents?: true

Size: 858 Bytes

Versions: 5

Compression:

Stored size: 858 Bytes

Contents

require 'json'

module Propono
  class UdpListenerError < ProponoError
  end

  class UdpListener

    def self.listen(&processor)
      new(&processor).listen
    end

    def initialize(&processor)
      raise UdpListenerError.new("Please provide a block to call for each message") unless block_given?
      @processor = processor
    end

    def listen
      loop { receive_and_process }
    end

    private

    def receive_and_process
      udp_data = socket.recvfrom(1024)[0]
      Thread.new { process_udp_data(udp_data) }
    end

    def process_udp_data(udp_data)
      json = JSON.parse(udp_data)
      @processor.call(json['topic'], json['message'])
    end

    def socket
      @socket ||= begin
        socket = UDPSocket.new
        socket.bind(Propono.config.udp_host, Propono.config.udp_port)
        socket
      end
    end
  end
end


Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
propono-0.8.2 lib/propono/services/udp_listener.rb
propono-0.8.0 lib/propono/services/udp_listener.rb
propono-0.7.0 lib/propono/services/udp_listener.rb
propono-0.6.3 lib/propono/services/udp_listener.rb
propono-0.6.1 lib/propono/services/udp_listener.rb