Class: Lancat::Sender

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

Instance Method Summary collapse

Constructor Details

#initialize(verbose, timeout, input) ⇒ Sender

Returns a new instance of Sender.



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

def initialize(verbose, timeout, input)
  @verbose = verbose
  @timeout = timeout
  @input = input
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/lancat/sender.rb', line 12

def start
  server = TCPServer.new(0)
  begin
    _, port, _, _ = server.addr(:numeric)

    STDERR.puts "Listening on port #{port}..." if @verbose

    # keep broadcasting packet indicating our IP/port, stop after timeout
    # or after a connection arrives
    client = nil
    multicast_sock = UDPSocket.new(Socket::AF_INET)
    begin
      multicast_sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, [1].pack('i'))
      multicast_sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_TTL, [1].pack('i'))

      msg = [port].pack('S>')

      for i in 1..@timeout
        STDERR.puts "Broadcast attempt #{i}..." if @verbose
        multicast_sock.send(msg, 0, MULTICAST_ADDR, MULTICAST_PORT)
        sleep 1

        begin
          client = server.accept_nonblock
          break if not client.nil?
        rescue IO::WaitReadable
          # ignore
        end
      end
    ensure
      multicast_sock.close
    end

    abort 'lancat: Timeout' if client.nil?

    _, _, _, remote = client.peeraddr(:numeric)
    STDERR.puts "Connection from #{remote}, writing data..." if @verbose

    loop do
      begin
        data = STDIN.readpartial(4096)
        client.write(data)
      rescue EOFError
        break
      end
    end
  ensure
    server.close
  end

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