Class: Torrenter::Peer

Inherits:
Object
  • Object
show all
Defined in:
lib/torrenter/peer/buffer_state.rb,
lib/torrenter/peer.rb,
lib/torrenter/peer/seed.rb

Overview

instead of initialiazing it with the buffer,

Defined Under Namespace

Classes: BufferState, Seed

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ip, port, params = {}) ⇒ Peer

Returns a new instance of Peer.



4
5
6
7
8
9
10
# File 'lib/torrenter/peer.rb', line 4

def initialize(ip, port, params={})
  @ip = ip
  @port = port
  @info_hash = params[:info_hash]
  @piece_length = params[:left]
  @peer_state   = false
end

Instance Attribute Details

#bufferObject (readonly)

Returns the value of attribute buffer.



3
4
5
# File 'lib/torrenter/peer.rb', line 3

def buffer
  @buffer
end

#ipObject (readonly)

Returns the value of attribute ip.



3
4
5
# File 'lib/torrenter/peer.rb', line 3

def ip
  @ip
end

#peer_stateObject (readonly)

Returns the value of attribute peer_state.



3
4
5
# File 'lib/torrenter/peer.rb', line 3

def peer_state
  @peer_state
end

#socketObject (readonly)

Returns the value of attribute socket.



3
4
5
# File 'lib/torrenter/peer.rb', line 3

def socket
  @socket
end

Instance Method Details

#connectObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/torrenter/peer.rb', line 12

def connect
  puts "\nConnecting to IP: #{@ip} PORT: #{@port}"
  begin
    Timeout::timeout(1) { @socket = TCPSocket.new(@ip, @port) }
  rescue Timeout::Error
    puts "Timed out."
  rescue Errno::EADDRNOTAVAIL
    puts "Address not available."
  rescue Errno::ECONNREFUSED
    puts "Connection refused."
  rescue Errno::ECONNRESET
    puts "bastards."
  end

  if @socket
    puts "Connected!"
    @peer_state = true
    @buffer = BufferState.new(@socket, @info_hash)
    @buffer.send(handshake)
  else
    @peer_state = false
  end
end

#connected?Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/torrenter/peer.rb', line 49

def connected?
  @peer_state
end

#connection_state(index, blk) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/torrenter/peer.rb', line 36

def connection_state(index, blk)
  if @socket.closed?
    @peer_state = false
    @buffer.current_piece = :available
  else
    @buffer.messager(index, blk)
  end
end

#handshakeObject



45
46
47
# File 'lib/torrenter/peer.rb', line 45

def handshake
  "#{PROTOCOL}#{@info_hash}#{PEER_ID}"
end