mirror of
https://github.com/OffchainLabs/prysm.git
synced 2026-01-10 07:58:22 -05:00
Add feed example
Former-commit-id: c2752225dd7c5aa19b8e1bd79f4513493e4cfbda [formerly cb091e596b79767eee5b312df94054d13be0f698] Former-commit-id: 2471f1863d552209ee48324b2d26710b9ea246d8
This commit is contained in:
42
sharding/p2p/feed_example_test.go
Normal file
42
sharding/p2p/feed_example_test.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package p2p
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Feeds can tbe use to subscribe to any type of message.
|
||||
func ExampleServer_Feed() {
|
||||
s, err := NewServer()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Let's wait for a puzzle from our peers then try to solve it.
|
||||
type Puzzle struct {
|
||||
Challenge string
|
||||
Answer string
|
||||
}
|
||||
|
||||
feed, err := s.Feed(Puzzle{})
|
||||
if err != nil {
|
||||
// This shouldn't happen, but we should handle it anyway.
|
||||
panic(err)
|
||||
}
|
||||
|
||||
ch := make(chan Message, 5) // Small buffer size. I don't expect many puzzles.
|
||||
sub := feed.Subscribe(ch)
|
||||
|
||||
// Always close these resources.
|
||||
defer sub.Unsubscribe()
|
||||
defer close(ch)
|
||||
|
||||
// Wait until we have a puzzle to solve.
|
||||
msg := <-ch
|
||||
puzzle := msg.Data.(Puzzle)
|
||||
|
||||
fmt.Printf("Received puzzle %s from peer %v\n", puzzle, msg.Peer)
|
||||
|
||||
if puzzle.Answer == "fourteen" {
|
||||
fmt.Println("I solved the puzzle!")
|
||||
} else {
|
||||
fmt.Println("The answer isn't \"fourteen\"... giving up")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user