Class: BlinkyCloud::Listener

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

Constant Summary collapse

BIND_ADDR =
"0.0.0.0"

Constants inherited from Base

Base::MULTICAST_ADDR, Base::PORT

Instance Method Summary collapse

Methods inherited from Base

#socket

Instance Method Details

#listen(callback) ⇒ Object



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

def listen(callback)
  socket = UDPSocket.new
  membership = IPAddr.new(MULTICAST_ADDR).hton + IPAddr.new(BIND_ADDR).hton

  socket.setsockopt(:IPPROTO_IP, :IP_ADD_MEMBERSHIP, membership)
  begin
    socket.setsockopt(:SOL_SOCKET, :SO_REUSEPORT, 1)
  rescue SocketError
  end
  begin
    socket.setsockopt(:SOL_SOCKET, :SO_REUSEADDR, 1)
  rescue SocketError
  end

  socket.bind(BIND_ADDR, PORT)

  loop do
    message, _ = socket.recvfrom(255)
    callback.call(message)
  end
end