@cryptotaxi247 / kubo / commits / 8b8a600a8

add dial and listen methods to the core for super awesomeness

Jeromy committed Feb 13, 2015 at 07:39 UTC 8b8a600a817ca18d0f57bbec5f72ed1be3e56bd4
1 file changed +56
core/net.go new
+56
@@ -0,0 +1,56 @@
1 +package core
2 +
3 +import (
4 + context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
5 + net "github.com/jbenet/go-ipfs/p2p/net"
6 + peer "github.com/jbenet/go-ipfs/p2p/peer"
7 + pro "github.com/jbenet/go-ipfs/p2p/protocol"
8 +)
9 +
10 +type ipfsListener struct {
11 + nd *IpfsNode
12 + conCh chan net.Stream
13 + proto pro.ID
14 + ctx context.Context
15 + cancel func()
16 +}
17 +
18 +func (il *ipfsListener) Accept() (net.Stream, error) {
19 + select {
20 + case c := <-il.conCh:
21 + return c, nil
22 + case <-il.ctx.Done():
23 + return nil, il.ctx.Err()
24 + }
25 +}
26 +
27 +func (il *ipfsListener) Close() error {
28 + il.cancel()
29 + // TODO: unregister handler from peerhost
30 + return nil
31 +}
32 +
33 +func (nd *IpfsNode) Listen(protocol string) (*ipfsListener, error) {
34 + ctx, cancel := context.WithCancel(nd.Context())
35 +
36 + list := &ipfsListener{
37 + proto: pro.ID(protocol),
38 + conCh: make(chan net.Stream),
39 + ctx: ctx,
40 + cancel: cancel,
41 + }
42 +
43 + nd.PeerHost.SetStreamHandler(list.proto, func(s net.Stream) {
44 + select {
45 + case list.conCh <- s:
46 + case <-ctx.Done():
47 + s.Close()
48 + }
49 + })
50 +
51 + return list, nil
52 +}
53 +
54 +func (nd *IpfsNode) Dial(protocol string, p peer.ID) (net.Stream, error) {
55 + return nd.PeerHost.NewStream(pro.ID(protocol), p)
56 +}