Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
Dec 31, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions examples/chat-with-mdns/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,29 +57,37 @@ func handleStream(stream net.Stream) {

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
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

```go
n := &discoveryNotifee{}
ser.RegisterNotifee(n)
ser.Start()
```



4. **Open streams to peers found.**

Finally we open stream to the peers we found, as we find them

```go
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")

if err := host.Connect(ctx, peer); err != nil {
fmt.Println("Connection failed:", err)
continue
}

// open a stream, this stream will be handled by handleStream other end
Expand Down
Loading