@cryptotaxi247 / kubo / commits / 73bd91a22

implement listening on swarm object

Jeromy committed Jul 28, 2014 at 20:46 UTC 73bd91a224c415deca62e3bfff70d6aca49de4ba
1 file changed +50 -2
swarm/swarm.go
+50 -2
@@ -3,7 +3,10 @@ package swarm
3 import (
4 "fmt"
5 peer "github.com/jbenet/go-ipfs/peer"
6 + ma "github.com/jbenet/go-multiaddr"
7 + u "github.com/jbenet/go-ipfs/util"
8 "sync"
9 + "net"
10 )
11
12 // Message represents a packet of information sent to or received from a
@@ -42,19 +45,64 @@ type Swarm struct {
45 Chan *Chan
46 conns ConnMap
47 connsLock sync.RWMutex
48 +
49 + local *peer.Peer
50 }
51
52 // NewSwarm constructs a Swarm, with a Chan.
48 -func NewSwarm() *Swarm {
53 +func NewSwarm(local *peer.Peer) *Swarm {
54 s := &Swarm{
55 Chan: NewChan(10),
56 conns: ConnMap{},
57 + local: local,
58 }
59 go s.fanOut()
60 return s
61 }
62
57 -// Close closes a swam.
63 +// Open listeners for each network the swarm should listen on
64 +func (s *Swarm) Listen() {
65 + for _,addr := range s.local.Addresses {
66 + err := s.connListen(addr)
67 + if err != nil {
68 + u.PErr("Failed to listen on: %s [%s]", addr, err)
69 + }
70 + }
71 +}
72 +
73 +// Listen for new connections on the given multiaddr
74 +func (s *Swarm) connListen(maddr *ma.Multiaddr) error {
75 + netstr, addr, err := maddr.DialArgs()
76 + if err != nil {
77 + return err
78 + }
79 +
80 + list, err := net.Listen(netstr, addr)
81 + if err != nil {
82 + return err
83 + }
84 +
85 + // Accept and handle new connections on this listener until it errors
86 + go func() {
87 + for {
88 + nconn,err := list.Accept()
89 + if err != nil {
90 + u.PErr("Failed to accept connection: %s - %s", netstr, addr)
91 + return
92 + }
93 + go s.handleNewConn(nconn)
94 + }
95 + }()
96 +
97 + return nil
98 +}
99 +
100 +// Handle getting ID from this peer and adding it into the map
101 +func (s *Swarm) handleNewConn(nconn net.Conn) {
102 + panic("Not yet implemented!")
103 +}
104 +
105 +// Close closes a swarm.
106 func (s *Swarm) Close() {
107 s.connsLock.RLock()
108 l := len(s.conns)