-
Notifications
You must be signed in to change notification settings - Fork 1
/
send.go
111 lines (100 loc) · 2.17 KB
/
send.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package dagchain
import (
"encoding/gob"
"time"
)
// the outer application send messages
func localSend(node *Node) {
for {
select {
case raw := <-node.send:
now := time.Now().UnixNano()
r := Request{
ID: now,
Command: NormalRequest,
Data: raw,
From: node.nodeAddr,
}
lock.Lock()
sendPackets[r.ID] = make([]*Packet, 0)
sendDatas[r.ID] = r
lock.Unlock()
n := 0
if node.seedAddr != "" {
// send to the seed
encoder := gob.NewEncoder(node.seedConn)
encoder.Encode(r)
lock.Lock()
sendPackets[r.ID] = append(sendPackets[r.ID], &Packet{
Addr: node.seedAddr,
})
lock.Unlock()
n++
}
// send to the downstream
for addr, conn := range node.downstreams {
encoder := gob.NewEncoder(conn)
encoder.Encode(r)
lock.Lock()
sendPackets[r.ID] = append(sendPackets[r.ID], &Packet{
Addr: addr,
})
lock.Unlock()
n++
}
// nothing happend, do some sweeping work.
if n == 0 {
lock.Lock()
delete(sendPackets, r.ID)
delete(sendDatas, r.ID)
lock.Unlock()
}
}
}
}
// receive remote node's messages, and we will route to other nodes and the outer application
func routeSend(node *Node, r *Request) {
now := time.Now().UnixNano()
newR := Request{
ID: now,
Command: NormalRequest,
Data: r.Data,
From: node.nodeAddr,
}
lock.Lock()
sendPackets[newR.ID] = make([]*Packet, 0)
sendDatas[newR.ID] = newR
lock.Unlock()
n := 0
if r.From != node.seedAddr && node.seedAddr != "" {
encoder := gob.NewEncoder(node.seedConn)
encoder.Encode(newR)
lock.Lock()
sendPackets[newR.ID] = append(sendPackets[newR.ID], &Packet{
Addr: node.seedAddr,
})
lock.Unlock()
n++
}
for addr, conn := range node.downstreams {
if r.From != addr && addr != "" {
encoder := gob.NewEncoder(conn)
encoder.Encode(newR)
lock.Lock()
sendPackets[newR.ID] = append(sendPackets[newR.ID], &Packet{
Addr: addr,
})
lock.Unlock()
n++
}
}
// nothing happend, do some sweeping work.
if n == 0 {
lock.Lock()
delete(sendPackets, newR.ID)
delete(sendDatas, newR.ID)
lock.Unlock()
}
// send to the outer application
node.recv <- r
}