Peer to Peer
#Peer to Peer: The peer to peer (p2p) package (Elastos.ELA.SideChain.ESC/p2p) allows you to rapidly and easily add p2p networking to any type of application. The p2p package is set up in a modular structure where extending it with your own additional sub protocols is easy and straightforward.
Starting the p2p service only requires you to setup a p2p.Server{}
with a few settings:
If we want to extend the capabilities of our p2p server, we need to pass it an additional sub protocol in the Protocol: []p2p.Protocol{}
array.
An additional sub protocol that has the ability to respond to the message "foo" with "bar" requires you to setup a p2p.Protocol{}
:
A sub-protocol object in the p2p package is called
Protocol{}
. Each time a peer connects with the capability of handling this type of protocol, it will use thisThe name of your protocol to identify the protocol on the network
The version of the protocol
The amount of messages this protocol relies on. Because the p2p is extendible and has the ability to send an arbitrary amount of messages, (with a type, which we'll see later) the p2p handler needs to know how much space it must reserve for your protocol - this is to ensure consensus can be reached between the peers doing a negotiation over the message IDs. Our protocol supports only one
message
(as you'll see later).The main handler of your protocol. We've left this intentionally blank for now. The
peer
variable is the peer connected to you and provides you with some basic information regarding the peer. Thews
variable, which is a reader and writer, allows you to communicate with the peer. If a message is being sent to us by that peer, theMsgReadWriter
will handle it, and vice versa.
Lets fill in the blanks and create a Let'suseful peer by allowing it to communicate with another:
The one and only message we know about
A typed string we decode in to
ReadMsg
waits on the line until it receives a message (an error or EOF)In case of an error during reading, it's best to return that error and let the p2p server handle it. This usually results in a disconnect from the peer
msg
contains two fields and a decoding method:Code
contains the message id,Code == messageId
(i.e., 0)Payload
the contents of the messageDecode(<ptr>)
is a helper method for: takemsg.Payload
and decodes the rest of the message in to the given interface. If it fails it will return an error
If the message we decoded was
foo
, respond with aNewMessage
using themessageId
message identifier and the messagebar
. Thebar
message would be handled in thedefault
case in the same switch
With this completed, we'd have a working p2p server with a message passing sub protocol.
Last updated