-
Notifications
You must be signed in to change notification settings - Fork 254
/
mdns.go
48 lines (40 loc) · 1.13 KB
/
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
43
44
45
46
47
48
package extension
import (
"context"
"time"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
discovery "github.com/libp2p/go-libp2p/p2p/discovery/mdns_legacy"
)
// MDNS mdns
type MDNS struct {
Service discovery.Service
notifee *discoveryNotifee
}
//用于局域网内节点发现
type discoveryNotifee struct {
PeerChan chan peer.AddrInfo
}
// HandlePeerFound is a interface to be called when new peer is found
func (n *discoveryNotifee) HandlePeerFound(pi peer.AddrInfo) {
n.PeerChan <- pi
}
// NewMDNS Initialize the MDNS service
func NewMDNS(ctx context.Context, peerhost host.Host, serviceTag string) (*MDNS, error) {
ser, err := discovery.NewMdnsService(ctx, peerhost, time.Minute*1, serviceTag)
if err != nil {
return nil, err
}
//register with service so that we get notified about peer discovery
notifee := &discoveryNotifee{}
notifee.PeerChan = make(chan peer.AddrInfo)
ser.RegisterNotifee(notifee)
mnds := new(MDNS)
mnds.Service = ser
mnds.notifee = notifee
return mnds, nil
}
// PeerChan returns a peer channel
func (m *MDNS) PeerChan() chan peer.AddrInfo {
return m.notifee.PeerChan
}