You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.5 KiB

9 years ago
  1. # `tendermint/go-p2p`
  2. `tendermint/go-p2p` provides an abstraction around peer-to-peer communication.<br/>
  3. ## Peer/MConnection/Channel
  4. Each peer has one `MConnection` (multiplex connection) instance.
  5. __multiplex__ *noun* a system or signal involving simultaneous transmission of
  6. several messages along a single channel of communication.
  7. Each `MConnection` handles message transmission on multiple abstract communication
  8. `Channel`s. Each channel has a globally unique byte id.
  9. The byte id and the relative priorities of each `Channel` are configured upon
  10. initialization of the connection.
  11. There are two methods for sending messages:
  12. ```go
  13. func (m MConnection) Send(chID byte, msg interface{}) bool {}
  14. func (m MConnection) TrySend(chID byte, msg interface{}) bool {}
  15. ```
  16. `Send(chID, msg)` is a blocking call that waits until `msg` is successfully queued
  17. for the channel with the given id byte `chID`. The message `msg` is serialized
  18. using the `tendermint/wire` submodule's `WriteBinary()` reflection routine.
  19. `TrySend(chID, msg)` is a nonblocking call that returns false if the channel's
  20. queue is full.
  21. `Send()` and `TrySend()` are also exposed for each `Peer`.
  22. ## Switch/Reactor
  23. The `Switch` handles peer connections and exposes an API to receive incoming messages
  24. on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one
  25. or more `Channels`. So while sending outgoing messages is typically performed on the peer,
  26. incoming messages are received on the reactor.
  27. ```go
  28. // Declare a MyReactor reactor that handles messages on MyChannelID.
  29. type MyReactor struct{}
  30. func (reactor MyReactor) GetChannels() []*ChannelDescriptor {
  31. return []*ChannelDescriptor{ChannelDescriptor{ID:MyChannelID, Priority: 1}}
  32. }
  33. func (reactor MyReactor) Receive(chID byte, peer *Peer, msgBytes []byte) {
  34. r, n, err := bytes.NewBuffer(msgBytes), new(int64), new(error)
  35. msgString := ReadString(r, n, err)
  36. fmt.Println(msgString)
  37. }
  38. // Other Reactor methods omitted for brevity
  39. ...
  40. switch := NewSwitch([]Reactor{MyReactor{}})
  41. ...
  42. // Send a random message to all outbound connections
  43. for _, peer := range switch.Peers().List() {
  44. if peer.IsOutbound() {
  45. peer.Send(MyChannelID, "Here's a random message")
  46. }
  47. }
  48. ```
  49. ### PexReactor/AddrBook
  50. A `PEXReactor` reactor implementation is provided to automate peer discovery.
  51. ```go
  52. book := p2p.NewAddrBook(addrBookFilePath)
  53. pexReactor := p2p.NewPEXReactor(book)
  54. ...
  55. switch := NewSwitch([]Reactor{pexReactor, myReactor, ...})
  56. ```