Browse Source

chore: update chat-with-mdns example readme (#2678)

* chore: update readme for example chat-with-mdns

* update old example code
pull/2680/head
Halimao 10 months ago
committed by GitHub
parent
commit
5286cdafab
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 16
      examples/chat-with-mdns/README.md

16
examples/chat-with-mdns/README.md

@ -57,29 +57,37 @@ func handleStream(stream net.Stream) {
3. **Find peers nearby using mdns** 3. **Find peers nearby using mdns**
Start [mdns discovery](https://godoc.org/github.com/libp2p/go-libp2p/p2p/discovery#NewMdnsService) service in host. New [mdns discovery](https://godoc.org/github.com/libp2p/go-libp2p/p2p/discovery#NewMdnsService) service in host.
```go ```go
ser, err := discovery.NewMdnsService(peerhost, rendezvous) notifee := &discoveryNotifee{PeerChan: make(chan peer.AddrInfo)}
ser, err := discovery.NewMdnsService(peerhost, rendezvous, notifee)
``` ```
register [Notifee interface](https://godoc.org/github.com/libp2p/go-libp2p/p2p/discovery#Notifee) with service so that we get notified about peer discovery register [Notifee interface](https://godoc.org/github.com/libp2p/go-libp2p/p2p/discovery#Notifee) with service so that we get notified about peer discovery
```go ```go
n := &discoveryNotifee{} ser.Start()
ser.RegisterNotifee(n)
``` ```
4. **Open streams to peers found.** 4. **Open streams to peers found.**
Finally we open stream to the peers we found, as we find them Finally we open stream to the peers we found, as we find them
```go ```go
peer := <-peerChan // will block until we discover a peer peer := <-peerChan // will block until we discover a peer
// this is used to avoid call `NewStream` from both side
if peer.ID > host.ID() {
// if other end peer id greater than us, don't connect to it, just wait for it to connect us
fmt.Println("Found peer:", peer, " id is greater than us, wait for it to connect to us")
continue
}
fmt.Println("Found peer:", peer, ", connecting") fmt.Println("Found peer:", peer, ", connecting")
if err := host.Connect(ctx, peer); err != nil { if err := host.Connect(ctx, peer); err != nil {
fmt.Println("Connection failed:", err) fmt.Println("Connection failed:", err)
continue
} }
// open a stream, this stream will be handled by handleStream other end // open a stream, this stream will be handled by handleStream other end

Loading…
Cancel
Save