conn.go 1.72 KB
Newer Older
1 2 3
package swarm

import (
4 5 6 7 8 9
	"fmt"
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
	msgio "github.com/jbenet/go-msgio"
	ma "github.com/jbenet/go-multiaddr"
	"net"
10 11
)

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
12
// ChanBuffer is the size of the buffer in the Conn Chan
13 14
const ChanBuffer = 10

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
15
// Conn represents a connection to another Peer (IPFS Node).
16
type Conn struct {
17 18 19
	Peer *peer.Peer
	Addr *ma.Multiaddr
	Conn net.Conn
20

21 22 23
	Closed   chan bool
	Outgoing *msgio.Chan
	Incoming *msgio.Chan
24 25
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
26
// ConnMap maps Keys (Peer.IDs) to Connections.
27
type ConnMap map[u.Key]*Conn
28

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
29 30
// Dial connects to a particular peer, over a given network
// Example: Dial("udp", peer)
31
func Dial(network string, peer *peer.Peer) (*Conn, error) {
32 33 34 35
	addr := peer.NetAddress(network)
	if addr == nil {
		return nil, fmt.Errorf("No address for network %s", network)
	}
36

37 38 39 40
	network, host, err := addr.DialArgs()
	if err != nil {
		return nil, err
	}
41

42 43 44 45
	nconn, err := net.Dial(network, host)
	if err != nil {
		return nil, err
	}
46

47 48 49 50
	conn := &Conn{
		Peer: peer,
		Addr: addr,
		Conn: nconn,
51
	}
52

53 54 55 56 57 58 59 60
	newConnChans(conn)
	return conn, nil
}

// Construct new channels for given Conn.
func newConnChans(c *Conn) error {
	if c.Outgoing != nil || c.Incoming != nil {
		return fmt.Errorf("Conn already initialized")
61
	}
62

63 64 65
	c.Outgoing = msgio.NewChan(10)
	c.Incoming = msgio.NewChan(10)
	c.Closed = make(chan bool, 1)
66

67 68 69 70
	go c.Outgoing.WriteTo(c.Conn)
	go c.Incoming.ReadFrom(c.Conn, 1<<12)

	return nil
71 72
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
73
// Close closes the connection, and associated channels.
74
func (s *Conn) Close() error {
75
	if s.Conn == nil {
76
		return fmt.Errorf("Already closed") // already closed
77
	}
78

79 80 81 82 83 84 85 86
	// closing net connection
	err := s.Conn.Close()
	s.Conn = nil
	// closing channels
	s.Incoming.Close()
	s.Outgoing.Close()
	s.Closed <- true
	return err
87
}