kubo/core/corenet/net.go
Jeromy b15470d548
bubble up updates from go-multihash changes
License: MIT
Signed-off-by: Jeromy <jeromyj@gmail.com>
2017-04-20 20:28:04 +02:00

66 lines
1.5 KiB
Go

package corenet
import (
"time"
context "context"
core "github.com/ipfs/go-ipfs/core"
pstore "gx/ipfs/QmNUVzEjq3XWJ89hegahPvyfJbTXgTaom48pLb7YBD9gHQ/go-libp2p-peerstore"
net "gx/ipfs/QmVHSBsn8LEeay8m5ERebgUVuhzw838PsyTttCmP6GMJkg/go-libp2p-net"
pro "gx/ipfs/QmZNkThpqfVXs9GNbexPrfBbXSLNYeKrE7jwFM2oqHbyqN/go-libp2p-protocol"
peer "gx/ipfs/QmdS9KpbDyPrieswibZhkod1oXqRwZJrUPzxCofAMWpFGq/go-libp2p-peer"
)
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, cancel := context.WithTimeout(nd.Context(), time.Second*30)
defer cancel()
err := nd.PeerHost.Connect(ctx, pstore.PeerInfo{ID: p})
if err != nil {
return nil, err
}
return nd.PeerHost.NewStream(nd.Context(), p, pro.ID(protocol))
}