/
net.go
63 lines (53 loc) · 1.33 KB
/
net.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package corenet
import (
"time"
context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
core "github.com/jbenet/go-ipfs/core"
net "github.com/jbenet/go-ipfs/p2p/net"
peer "github.com/jbenet/go-ipfs/p2p/peer"
pro "github.com/jbenet/go-ipfs/p2p/protocol"
)
type ipfsListener struct {
conCh chan net.Stream
proto pro.ID
ctx context.Context
cancel func()
}
func (il *ipfsListener) Accept() (net.Stream, error) {
select {
case c := <-il.conCh:
return c, nil
case <-il.ctx.Done():
return nil, il.ctx.Err()
}
}
func (il *ipfsListener) Close() error {
il.cancel()
// TODO: unregister handler from peerhost
return nil
}
func Listen(nd *core.IpfsNode, protocol string) (*ipfsListener, error) {
ctx, cancel := context.WithCancel(nd.Context())
list := &ipfsListener{
proto: pro.ID(protocol),
conCh: make(chan net.Stream),
ctx: ctx,
cancel: cancel,
}
nd.PeerHost.SetStreamHandler(list.proto, func(s net.Stream) {
select {
case list.conCh <- s:
case <-ctx.Done():
s.Close()
}
})
return list, nil
}
func Dial(nd *core.IpfsNode, p peer.ID, protocol string) (net.Stream, error) {
ctx, _ := context.WithTimeout(nd.Context(), time.Second*30)
err := nd.PeerHost.Connect(ctx, peer.PeerInfo{ID: p})
if err != nil {
return nil, err
}
return nd.PeerHost.NewStream(pro.ID(protocol), p)
}