mirror of
https://gitlab.com/pulsechaincom/prysm-pulse.git
synced 2025-01-09 11:11:20 +00:00
9ab76dc1f6
Former-commit-id: 797bc1cf3a759f2a55dbf1ce790c3f599682448c [formerly 8f4e5d953c3e553944db263a76c142ffccad516d] Former-commit-id: c7c1e3e2d340c8cd5f97e4549fa46a7959be06c6
47 lines
978 B
Go
47 lines
978 B
Go
package p2p
|
|
|
|
import "fmt"
|
|
|
|
// Feeds can be 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, ok := msg.Data.(Puzzle)
|
|
|
|
if !ok {
|
|
panic("Received a message that wasn't a 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")
|
|
}
|
|
}
|