Class: Multicast::Listener

Inherits:
Object
  • Object
show all
Defined in:
lib/multicast/listener.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Listener

Returns a new instance of Listener.



5
6
7
8
# File 'lib/multicast/listener.rb', line 5

def initialize(opts={})
  @group  = opts[:group]
  @port   = opts[:port]
end

Instance Attribute Details

#groupObject

Returns the value of attribute group.



3
4
5
# File 'lib/multicast/listener.rb', line 3

def group
  @group
end

#portObject

Returns the value of attribute port.



3
4
5
# File 'lib/multicast/listener.rb', line 3

def port
  @port
end

Instance Method Details

#listen(&block) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/multicast/listener.rb', line 10

def listen(&block)
  
  ip =  IPAddr.new(@group).hton + IPAddr.new("0.0.0.0").hton
  sock = UDPSocket.new
  sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, ip)
  sock.bind(Socket::INADDR_ANY, @port)
  
  loop do
    begin
      msg, info = sock.recvfrom(1024)
      message = Message.new(:message => msg, :hostname => info[2], :ip => info[3], :port => info[1])
      yield(message)

    rescue Interrupt
      sock.close
      puts "\n---> Exiting" 
      exit
    end

  end
end