Class: Lancat::Receiver

Inherits:
Object
  • Object
show all
Defined in:
lib/lancat/receiver.rb

Instance Method Summary collapse

Constructor Details

#initialize(verbose, timeout, output) ⇒ Receiver

Returns a new instance of Receiver.



6
7
8
9
10
# File 'lib/lancat/receiver.rb', line 6

def initialize(verbose, timeout, output)
  @verbose = verbose
  @timeout = timeout
  @output = output
end

Instance Method Details

#startObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/lancat/receiver.rb', line 12

def start
  STDERR.puts 'Waiting for broadcasts...' if @verbose

  addr = nil
  port = nil

  multicast_sock = UDPSocket.new(Socket::AF_INET)
  begin
    ips = IPAddr.new(MULTICAST_ADDR).hton + IPAddr.new('0.0.0.0').hton
    multicast_sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, ips)
    multicast_sock.bind(Socket::INADDR_ANY, MULTICAST_PORT)

    # TODO add support for receive timeout
    msg, addr = multicast_sock.recvfrom(2)
    port = msg.unpack('S>')[0]
    addr = addr[3]
  ensure
    multicast_sock.close
  end

  STDERR.puts "Connecting to #{addr}:#{port}..." if @verbose
  client = TCPSocket.new(addr, port)
  begin
    STDERR.puts 'Reading data...' if @verbose
    loop do
      begin
        data = client.readpartial(4096)
        STDOUT.write(data)
      rescue EOFError
        break
      end
    end
  ensure
    client.close
  end

  STDERR.puts 'Transfer complete.' if @verbose
end