1
0
mirror of https://github.com/ipfs/kubo.git synced 2025-09-13 00:38:34 +08:00
Files
kubo/core/corenet/net.go

57 lines
1.2 KiB
Go

package corenet
import (
context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.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) {
return nd.PeerHost.NewStream(pro.ID(protocol), p)
}