-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.go
49 lines (43 loc) · 1.25 KB
/
net.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package discovery
import (
"github.com/iain17/discovery/pb"
"net"
"time"
"fmt"
)
//Initiate a handshake procedure.
//See (l *ListenerService) process(c net.Conn) error for the receiving side.
func connect(h *net.TCPAddr, ln *LocalNode) (*RemoteNode, error) {
accepted := false
addr := h.String()
conn, errDial := net.Dial("tcp", addr)
defer func() {
//s.Close()
if !accepted && conn != nil{
conn.Close()
}
}()
if errDial != nil {
return nil, fmt.Errorf("error dialing %s: %s", h.String(), errDial.Error())
}
conn.SetDeadline(time.Now().Add(1 * time.Second))
rn := NewRemoteNode(conn, ln)
//Handshake dance.
//Wait for them to accept and send their peer info
rn.logger.Debug("Waiting for their peer info...")
peerInfo, err := pb.DecodePeerInfo(rn.conn, string(ln.discovery.network.ExportPublicKey()))
if err != nil {
return nil, fmt.Errorf("error at waiting for their peer info: %s", err.Error())
}
rn.logger.Debug("Received peer info...")
rn.Initialize(peerInfo)
conn.SetDeadline(time.Now().Add(5 * time.Second))
rn.logger.Debug("Sending our peer info")
err = ln.sendPeerInfo(rn.conn)
if err != nil {
return nil, fmt.Errorf("error sending our peer info: %s", err.Error())
}
rn.logger.Info("connected!")
accepted = true
return rn, nil
}