This repository has been archived by the owner on Mar 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 361
/
mdns.go
69 lines (58 loc) · 1.42 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package mdns
import (
"context"
"fmt"
"github.com/grandcat/zeroconf"
)
const (
instanceName = "bytomd"
serviceName = "bytom%sLanDiscover"
domainName = "local"
)
// Protocol decoration ZeroConf,which is a pure Golang library
// that employs Multicast DNS-SD.
type Protocol struct {
entries chan *zeroconf.ServiceEntry
server *zeroconf.Server
serviceName string
quite chan struct{}
}
// NewProtocol create a specific Protocol.
func NewProtocol(chainID string) *Protocol {
return &Protocol{
entries: make(chan *zeroconf.ServiceEntry),
serviceName: fmt.Sprintf(serviceName, chainID),
quite: make(chan struct{}),
}
}
func (p *Protocol) getLanPeerLoop(event chan LANPeerEvent) {
for {
select {
case entry := <-p.entries:
event <- LANPeerEvent{IP: entry.AddrIPv4, Port: entry.Port}
case <-p.quite:
return
}
}
}
func (p *Protocol) registerService(port int) error {
var err error
p.server, err = zeroconf.Register(instanceName, p.serviceName, domainName, port, nil, nil)
return err
}
func (p *Protocol) registerResolver(event chan LANPeerEvent) error {
go p.getLanPeerLoop(event)
resolver, err := zeroconf.NewResolver(nil)
if err != nil {
return err
}
return resolver.Browse(context.Background(), p.serviceName, domainName, p.entries)
}
func (p *Protocol) stopResolver() {
close(p.quite)
}
func (p *Protocol) stopService() {
if p.server != nil {
p.server.Shutdown()
}
}