github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/p2p/discover/mdns/mdns.go (about)

     1  package mdns
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/grandcat/zeroconf"
     8  )
     9  
    10  const (
    11  	instanceName = "bytomd"
    12  	serviceName  = "bytom%sLanDiscover"
    13  	domainName   = "local"
    14  )
    15  
    16  // Protocol decoration ZeroConf,which is a pure Golang library
    17  // that employs Multicast DNS-SD.
    18  type Protocol struct {
    19  	entries     chan *zeroconf.ServiceEntry
    20  	server      *zeroconf.Server
    21  	serviceName string
    22  	quite       chan struct{}
    23  }
    24  
    25  // NewProtocol create a specific Protocol.
    26  func NewProtocol(chainID string) *Protocol {
    27  	return &Protocol{
    28  		entries:     make(chan *zeroconf.ServiceEntry),
    29  		serviceName: fmt.Sprintf(serviceName, chainID),
    30  		quite:       make(chan struct{}),
    31  	}
    32  }
    33  
    34  func (p *Protocol) getLanPeerLoop(event chan LANPeerEvent) {
    35  	for {
    36  		select {
    37  		case entry := <-p.entries:
    38  			event <- LANPeerEvent{IP: entry.AddrIPv4, Port: entry.Port}
    39  		case <-p.quite:
    40  			return
    41  		}
    42  	}
    43  }
    44  
    45  func (p *Protocol) registerService(port int) error {
    46  	var err error
    47  	p.server, err = zeroconf.Register(instanceName, p.serviceName, domainName, port, nil, nil)
    48  	return err
    49  }
    50  
    51  func (p *Protocol) registerResolver(event chan LANPeerEvent) error {
    52  	go p.getLanPeerLoop(event)
    53  	resolver, err := zeroconf.NewResolver(nil)
    54  	if err != nil {
    55  		return err
    56  	}
    57  
    58  	return resolver.Browse(context.Background(), p.serviceName, domainName, p.entries)
    59  }
    60  
    61  func (p *Protocol) stopResolver() {
    62  	close(p.quite)
    63  }
    64  
    65  func (p *Protocol) stopService() {
    66  	if p.server != nil {
    67  		p.server.Shutdown()
    68  	}
    69  }