github.com/turingchain2020/turingchain@v1.1.21/system/p2p/dht/extension/mdns.go (about)

     1  package extension
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/libp2p/go-libp2p-core/host"
     8  	"github.com/libp2p/go-libp2p-core/peer"
     9  	"github.com/libp2p/go-libp2p/p2p/discovery"
    10  )
    11  
    12  // MDNS mdns
    13  type MDNS struct {
    14  	Service discovery.Service
    15  	notifee *discoveryNotifee
    16  }
    17  
    18  //用于局域网内节点发现
    19  type discoveryNotifee struct {
    20  	PeerChan chan peer.AddrInfo
    21  }
    22  
    23  // HandlePeerFound is a interface to be called when new peer is found
    24  func (n *discoveryNotifee) HandlePeerFound(pi peer.AddrInfo) {
    25  	n.PeerChan <- pi
    26  }
    27  
    28  // NewMDNS Initialize the MDNS service
    29  func NewMDNS(ctx context.Context, peerhost host.Host, serviceTag string) (*MDNS, error) {
    30  	ser, err := discovery.NewMdnsService(ctx, peerhost, time.Minute*1, serviceTag)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  
    35  	//register with service so that we get notified about peer discovery
    36  	notifee := &discoveryNotifee{}
    37  	notifee.PeerChan = make(chan peer.AddrInfo)
    38  	ser.RegisterNotifee(notifee)
    39  	mnds := new(MDNS)
    40  	mnds.Service = ser
    41  	mnds.notifee = notifee
    42  	return mnds, nil
    43  }
    44  
    45  // PeerChan returns a peer channel
    46  func (m *MDNS) PeerChan() chan peer.AddrInfo {
    47  	return m.notifee.PeerChan
    48  }