1
votes

I've implemented most of the BitTorrent protocol in Java. The problem is that for some reason none of the peers are sending me any of the pieces I request. (After 3 hours I received only 2 piece-messages)

My handshaking is as follows:

send 19
send "BitTorrent protocol"
send 8 zero'd reserved bytes
send info_hash (20 bytes)
send peer_id (20 bytes)

read 19
read "BitTorrent protocol"
read 8 reserved bytes
read info_hash. Compare with own info_hash
read peer_id

send unchoke

start listening for messages

I listen for messages in another thread as follows:

while(true)
    read length (4 bytes)
    read id (1 byte)
    if length == 0: continue //keep-alive message
    if id == 1: Stop all requests to this peer
    if id == 2: Continue all requests to this peer
    if id == 4: Read index from have-message and request piece if we don't have it
    if id == 5: If we have not already received bitfield. Read and store it. Request any pieces that we don't have yet
    if id == 7: Read index, begin and length. Read and store piece. Send have-message if a piece was fully downloaded

Can you see any problem with this approach? I've tried doing periodic keep-alive messages every minute, but that doesn't help. What's weird is that I'm receiving tons of bitfield-messages and maintaining 30+ active connections.

1

1 Answers

3
votes

This answer is pretty late, but I got linked to it so maybe this'll still be useful.

I think you have your ids mixed up. 0 is "choke" and 1 is "unchoke" (not 1 and 2). Also you might need to make sure you're triggering requests when you get unchoked too just in case you get the "have" message before that.