-
Notifications
You must be signed in to change notification settings - Fork 0
/
mdns.go
42 lines (35 loc) · 969 Bytes
/
mdns.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package mdns
import (
"context"
"fmt"
"time"
golog "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/p2p/discovery/mdns"
)
var log = golog.Logger("psrpc/mdns")
const connTimeout = time.Second * 10
// Start the MDNS discovery.
func Start(ctx context.Context, host host.Host) error {
service := mdns.NewMdnsService(host, mdns.ServiceName, &handler{
ctx: ctx,
host: host,
})
if err := service.Start(); err != nil {
return fmt.Errorf("staring mdns service: %s", err)
}
return nil
}
type handler struct {
ctx context.Context
host host.Host
}
// HandlePeerFound tries to connect to the discovered peer.
func (h *handler) HandlePeerFound(p peer.AddrInfo) {
ctx, cancel := context.WithTimeout(h.ctx, connTimeout)
defer cancel()
if err := h.host.Connect(ctx, p); err != nil {
log.Warnf("failed to connect to peer %s found by discovery: %v", p.ID, err)
}
}