Sha256: 920f74cb576e74ac15b42c7fe71dd02b9bb1e948d00235a194797c28c05a087c

Contents?: true

Size: 869 Bytes

Versions: 2

Compression:

Stored size: 869 Bytes

Contents

require 'socket'
require 'timeout'

module PulseMeter
  class UDPServer
    MAX_PACKET = 1024
  
    def initialize(host, port)
      @socket = UDPSocket.new
      @socket.do_not_reverse_lookup = true
      @socket.bind(host, port)
    end

    def start(max_packets = nil)
      while true do
        if max_packets
          break if max_packets <= 0
          max_packets -= 1
        end
        process_packet
      end
    end

    private

    def process_packet
      raw_data, _ = @socket.recvfrom(MAX_PACKET)
      data = parse_data(raw_data)
      data.each do |command|
        PulseMeter.redis.send(*command)
      end
    rescue StandardError => e
      PulseMeter.error "Error processing packet: #{e}"
    end

    def parse_data(data)
      JSON.parse(data)
    rescue
      PulseMeter.error "Bad redis data: #{data.inspect}"
      []
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
pulse-meter-0.4.4 lib/pulse-meter/udp_server.rb
pulse-meter-0.4.3 lib/pulse-meter/udp_server.rb