forked from fangj99/spider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
55 lines (47 loc) · 844 Bytes
/
table.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
package spider
import (
"net"
"sync"
)
//define const
const (
TableSize = 1024
HasFoundSize = 100000
)
var hasFound = make(map[string]bool, HasFoundSize)
var mutex sync.Mutex
//KNode define
type KNode struct {
ID ID
IP net.IP
Port int
}
//KTable define table
type KTable struct {
Nodes []*KNode
cap int64
//用于响应find_node请求
Snodes []*KNode
}
//Put node to table
func (table *KTable) Put(node *KNode) {
ids := string([]byte(node.ID))
mutex.Lock()
defer mutex.Unlock()
if _, ok := hasFound[ids]; !ok {
table.Nodes = append(table.Nodes, node)
hasFound[ids] = true
}
if len(table.Snodes) < 8 {
table.Snodes = append(table.Snodes, node)
}
}
//Pop node
func (table *KTable) Pop() *KNode {
if len(table.Nodes) > 0 {
n := table.Nodes[0]
table.Nodes = table.Nodes[1:]
return n
}
return nil
}