ipfs, libp2p, swarm notify

Data Structure

type Swarm struct {
	// Close refcount. This allows us to fully wait for the swarm to be torn
	// down before continuing.
	refs sync.WaitGroup

	local peer.ID
	peers peerstore.Peerstore

	conns struct {
		sync.RWMutex
		m map[peer.ID][]*Conn
	}

	listeners struct {
		sync.RWMutex

		ifaceListenAddres []ma.Multiaddr
		cacheEOL          time.Time

		m map[transport.Listener]struct{}
	}

	notifs struct {
		sync.RWMutex
		m map[network.Notifiee]struct{}
	}
	...

notifs is a map, indexed by network.Notifiee

notifiee Registration

IdConn: NewIDService()
Relay: NewAutoRelay()
BasicHost: NewHost()
DHT: NewDht()
Circuit: NewRelay()
NAT: NewAutoNAT()

Interface

type Notifiee interface {
	Listen(Network, ma.Multiaddr)      // called when network starts listening on an addr
	ListenClose(Network, ma.Multiaddr) // called when network stops listening on an addr
	Connected(Network, Conn)           // called when a connection opened
	Disconnected(Network, Conn)        // called when a connection closed
	OpenedStream(Network, Stream)      // called when a stream opened
	ClosedStream(Network, Stream)      // called when a stream closed

	// TODO
	// PeerConnected(Network, peer.ID)    // called when a peer connected
	// PeerDisconnected(Network, peer.ID) // called when a peer disconnected
}

Notify

swarm.go
addConn
	s.notifyAll(func(f network.Notifiee) { f.Connected(s, c) }
swarm_conn.go
addStream
	c.swarm.notifyAll(func(f network.Notifiee) { f.OpenedStream(c.swarm, s) }
doClose
		c.swarm.notifyAll(func(f network.Notifiee) { f.Disconnected(c.swarm, c) }
swarm_listen.go
AddListenAddr
	s.notifyAll(func(n network.Notifiee) { n.Listen(s, maddr) }
swarm_stream.go
remove
		s.conn.swarm.notifyAll(func(f network.Notifiee) { f.ClosedStream(s.conn.swarm, s) }
发布了11 篇原创文章 · 获赞 4 · 访问量 550

猜你喜欢

转载自blog.csdn.net/m0_37889044/article/details/104410024