-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
46 lines (40 loc) · 814 Bytes
/
listener.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
package go_libp2p_grpc
import (
"context"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/network"
manet "github.com/multiformats/go-multiaddr/net"
"io"
"net"
)
var _ net.Listener = (*listener)(nil)
type listener struct {
h host.Host
streamCh chan network.Stream
ctx context.Context
cancel context.CancelFunc
}
func (l listener) Accept() (net.Conn, error) {
select {
case <-l.ctx.Done():
return nil, io.EOF
case s := <-l.streamCh:
return &Conn{Stream: s}, nil
}
}
func (l listener) Close() error {
l.cancel()
return nil
}
func (l listener) Addr() net.Addr {
addrs := l.h.Network().ListenAddresses()
if len(addrs) > 0 {
for _, a := range addrs {
na, err := manet.ToNetAddr(a)
if err == nil {
return na
}
}
}
return fakeAddr()
}