Can't Download a Piece due to Connection Issues

I’m stuck on Stage #ND2.

I’m stuck in downloading the piece, for the first test of piece_0 the code works well and download all blocks, but at the second test of piece_11 there is a problem with peers’ connection.
I have tried different things, but I think this code structure and logic is the best I can provide

Here are my logs for piece_11 where the problem occurred:


I have added some custom logs for better readability.

I think the code snippet won’t be the best way to show the logic, so I have pushed the latest modifications to the remote repository, hoping that you can see and access it.

I use a Swarm class that owns all PeerConnection instances (it stores everything about a P2P connection and its state, such as choking and interest) and has references to TorrentFile, PieceDownload (handles the process of assembling and providing the needed missing blocks), and PeerMessageHandler (handles every message sent based on its type).

What Swarm does in the work method is that the swarm asks PeerConnections whether any of them have a message (looping) and handles it. While checking for messages, if a connection fails, it gets removed from the available peers to prevent infinite looping for already dead peers.

In Main, I treat the swarm as a black box, providing it with the data it needs about the file and peers, and then invoke the work method.

Thanks in advance for your time and your continuous help :heart:.

Hey @MaHmoudHaBlaSs, could you upload your code to GitHub and share the link? It will be much easier to debug if I can run it directly.

1 Like

Sure, here is the link MaHmoudHaBlaSs/BitTorrent

Piece length must be calculated per piece.
If the last piece is shorter, its block requests must respect that reduced length, otherwise peers may close the connection and that was the issue, I was assuming fixed piece length.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.