github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/core/corenet/net.go (about) 1 package corenet 2 3 import ( 4 "time" 5 6 context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context" 7 core "github.com/ipfs/go-ipfs/core" 8 net "github.com/ipfs/go-ipfs/p2p/net" 9 peer "github.com/ipfs/go-ipfs/p2p/peer" 10 pro "github.com/ipfs/go-ipfs/p2p/protocol" 11 ) 12 13 type ipfsListener struct { 14 conCh chan net.Stream 15 proto pro.ID 16 ctx context.Context 17 cancel func() 18 } 19 20 func (il *ipfsListener) Accept() (net.Stream, error) { 21 select { 22 case c := <-il.conCh: 23 return c, nil 24 case <-il.ctx.Done(): 25 return nil, il.ctx.Err() 26 } 27 } 28 29 func (il *ipfsListener) Close() error { 30 il.cancel() 31 // TODO: unregister handler from peerhost 32 return nil 33 } 34 35 func Listen(nd *core.IpfsNode, protocol string) (*ipfsListener, error) { 36 ctx, cancel := context.WithCancel(nd.Context()) 37 38 list := &ipfsListener{ 39 proto: pro.ID(protocol), 40 conCh: make(chan net.Stream), 41 ctx: ctx, 42 cancel: cancel, 43 } 44 45 nd.PeerHost.SetStreamHandler(list.proto, func(s net.Stream) { 46 select { 47 case list.conCh <- s: 48 case <-ctx.Done(): 49 s.Close() 50 } 51 }) 52 53 return list, nil 54 } 55 56 func Dial(nd *core.IpfsNode, p peer.ID, protocol string) (net.Stream, error) { 57 ctx, cancel := context.WithTimeout(nd.Context(), time.Second*30) 58 defer cancel() 59 err := nd.PeerHost.Connect(ctx, peer.PeerInfo{ID: p}) 60 if err != nil { 61 return nil, err 62 } 63 return nd.PeerHost.NewStream(pro.ID(protocol), p) 64 }