How are the messages encoded or sent/received by peers?
If there is a message
have: <len=开发者_Python百科0005><id=4><piece index>
How is this sent(in binary,how is it translated to binary?) and received?
Is there a specific order in which the messages are sent to peers?
I have read the specification but it leaves me with questions.
Thanks
I'll answer the ordering question.
In general, you can send any message at any time. But there are some messages which have special rules. The BITFIELD message has to be sent out early for instance. Most clients send PIECEs back in the order they were REQUESTed, but I don't think that is a requirement if memory serves.
In general the messages are of two types. One kind are control-oriented messages telling peers about general status (HAVE messages falls into this group). The other kind are data-oriented messages that actually transfers the file and requests new data from the peer. These message types are "interleaved" and one of the reasons you send PIECE messages no larger than 16 kilobytes is to make sure control messages can be interleaved in between. A trick is that when a PIECE message has been sent, then send all control-oriented messages by priority before the next PIECE message. That way, you quickly tell the other party of your intent.
There is also a "bug" in the original protocol which is solved by the FAST extension. It effectively make each REQUEST result in either a PIECE message or a REJECT-REQUEST message. This is another example of an ordering. If you get a REJECT-REQUEST message for something you never REQUESTED you disconnect the peer.
Prior to declaring the have
message the specification says:
All of the remaining messages in the protocol take the form of <length prefix><message ID><payload>. The length prefix is a four byte big-endian value. The message ID is a single decimal byte. The payload is message dependent.
You've got the binary format for length and id right there. The 'piece index' part is this message's specific payload. It should be four bytes long since the message has a fixed size of 5 bytes and 1 byte went to the message ID (viewing other messages with the same format should give you a clue).
精彩评论