listener.go 948 Bytes
Newer Older
1 2
package p2p

3 4 5 6
import (
	"sync"
)

7 8
type Listener interface {
	Protocol() string
Łukasz Magiera's avatar
Łukasz Magiera committed
9 10
	ListenAddress() string
	TargetAddress() string
11 12 13 14 15

	// Close closes the listener. Does not affect child streams
	Close() error
}

16 17 18 19 20 21
type listenerKey struct {
	proto  string
	listen string
	target string
}

22 23
// ListenerRegistry is a collection of local application proto listeners.
type ListenerRegistry struct {
24
	Listeners map[listenerKey]Listener
25
	lk        *sync.Mutex
26 27
}

28
// Register registers listenerInfo in this registry
29 30 31 32 33
func (r *ListenerRegistry) Register(l Listener) {
	r.lk.Lock()
	defer r.lk.Unlock()

	r.Listeners[getListenerKey(l)] = l
34 35 36
}

// Deregister removes p2p listener from this registry
37 38 39 40 41
func (r *ListenerRegistry) Deregister(k listenerKey) {
	r.lk.Lock()
	defer r.lk.Unlock()

	delete(r.Listeners, k)
42 43 44 45 46 47 48 49
}

func getListenerKey(l Listener) listenerKey {
	return listenerKey{
		proto:  l.Protocol(),
		listen: l.ListenAddress(),
		target: l.TargetAddress(),
	}
50
}