An overview on the peer messages protocol.
The client can use two protocols to share information with peers, TCP or uTP (over UDP). This data follows the bittorrent protocol specification, section peer messages.
So programmatically, a connection has to start between two clients. After the connection is set (through TCP or uTP), a bittorrent handshake is initiated by the client which grabbed remote peer's information (ip&port) from tracker or through DHT. This handshake contains the info_hash that identify the torrent this connection will be about.
Let's see first how Torrent data is truncated through the protocol. A piece is a part of the data you are sharing through the network. Not to get confused with a block, which is a section of a piece wrapped into a packet. The block is the granularity to share a piece through packets, and a piece is the granularity to share a Torrent through peers.
When the connection starts, both clients (local client, which I'll call LC and remote client, RC ) are choked and uninterested. Choked means "I won't answer any of your messages, too busy, but I might take them into account". Unchocked therefore means "I will answer your messages". Interested means of course that I'd like some pieces you have. Therefore, the state of a connection between two peers could be defined with those four states : LC_chocked?, LC_interested?, RC_chocked?, RC_interested? To warn RC that I'm (un)chocked or (un)interested, I have to send him (un)interested and (un)chocked messages, and reciprocally.
To inform each other which pieces they have, they can send a bitfield message just after handshaking. As it's name suggests, it is a bit string where each bit is set to 1
if the client has this peculiar piece, 0
otherwise.
So if LC is chocked and interested and RC has unchocked him, then he can send a request messages to ask for a block belonging to one piece he knows LC has thanks to bitfield message.
When a peer has received the entire piece, he could send a piece message to inform all it's remote peers so that they update the associated bitfield they are holding.
That is a very basic overview, and of course not all details are provided here, like the choking algorithm etc... If you want more details, check the two links I posted above, in the comment section (as a new user I can't have more than two links within a post).
1A beautiful answer! One quip: I believe seeds prefer to seed rarest, not the first pieces first. Not sure if this is an algorithm thing, but that's what I got from a torrent program once while messing with settings. – Gallifreyan – 2018-09-07T20:00:30.350