Implementing custom application protocols #3764
-
Hi there! Newbie question. I've been playing around with the examples and I'm liking rust-libp2p so far. I combined a few NetworkBehaviours and I fairly quickly had a working program that finds peers through mDNS, connects to them via TCP with asymmetric encryption and exchanges identification info. It was a breeze. Now I'd like to go beyond textbook examples. If I'm not mistaken, every example in the repo involves piecing together existing NetworkBehaviours into a composite data structure. What I'm looking for is some guidance on how to implement application-specific logic. Suppose I want both peers to be able to ask for the other peer's time, and respond to such requests if they occur. Peers should only send requests and responses if both are running Is this a use case that one of the off-the-shelf NetworkBehaviours can be adapted to? Should I roll my own NetworkBehaviour and corresponding ConnectionHandler? Should I hook any application-specific logic to the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
If your protocol is request-response style, you can use If it is not, you will have to implement the following traits on various structs:
For a simple protocol such as answering the current time, that state is available "inline" with the request, meaning you can directly answer it in the stream upgrade (look at However, for more complex state management, you want to use Have a look at how these traits are used. Unfortunately, there are many ways to solve this problem at the moment so there isn't one clear example to work from. I'd say |
Beta Was this translation helpful? Give feedback.
If your protocol is request-response style, you can use
libp2p-request-response
.If it is not, you will have to implement the following traits on various structs:
ConnectionHandler
to do the state management per connectionNetworkBehaviour
to do the state management across your entire protocolFor a simple protocol such as answering the current time, that state is available "inline" with the request, meaning you can directly answer it in the stream upgrade (look at
InboundUpgrade
trait and how it is used).However, for more complex state management, you want to use
ReadyUpgrade
, pass the stream to theConnectionHandler
and read and write to it there.Have a look at how these traits are …