Sha256: 66a82f9443d30a7a93b5cdb206b05df458d83b51f5f4680ae057e3324a431813

Contents?: true

Size: 847 Bytes

Versions: 3

Compression:

Stored size: 847 Bytes

Contents

module Noam
  class Beacon
    attr_reader :name, :host, :port

    def initialize(name, host, port)
      @name = name
      @host = host
      @port = port
    end

    def self.discover(net = "0.0.0.0")
      socket = UDPSocket.new
      begin
        socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true)
        socket.bind(net, Noam::BEACON_PORT)

        raise "Didn't see beacon after #{WAIT_TIME} seconds." unless message_received?(socket)

        data, addr = socket.recvfrom(MAX_RESPONSE_LENGTH)
        parsed_data = JSON.parse(data)
        Beacon.new(parsed_data[1], addr[2], parsed_data[2])
      ensure
        socket.close
      end
    end

    private

    MAX_RESPONSE_LENGTH = 1600
    WAIT_TIME = 10.0

    def self.message_received?(socket)
      IO.select([socket], [], [], WAIT_TIME) != nil
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
noam_lemma-0.2.1.2 lib/noam_lemma/beacon.rb
noam_lemma-0.2.1.1 lib/noam_lemma/beacon.rb
noam_lemma-0.2.1 lib/noam_lemma/beacon.rb