-
Notifications
You must be signed in to change notification settings - Fork 2
/
bucketset.rb
84 lines (72 loc) · 1.33 KB
/
bucketset.rb
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
require 'ipaddr'
require File.expand_path(File.dirname(__FILE__) + '/peer')
class BucketSet
def initialize
@@set = Hash.new
@@mutex = Mutex.new
@info = {
"bad" => 0,
"good" => 0,
}
end
def getlength
size = 0
@@mutex.synchronize do
size = @@set.size
end
return size
end
def insert(id, peer)
@@mutex.synchronize do
puts "insert " + id + " to bucketSet"
@@set[id] = peer
end
end
def delete(id)
@@mutex.synchronize do
puts "delect" + id + " at bucketSet"
@@set.delete(id)
end
end
def hasKey(id)
ishas = false
@@mutex.synchronize do
ishas = @@set.has_key?(id)
end
return ishas
end
def getPeer(id)
peer = nil
@@mutex.synchronize do
peer = @@set[id]
end
return peer
end
def update(sock, id)
goodnum = 0
badnum = 0
@@mutex.synchronize do
@@set.each do |k,v|
if v.isbad then badnum = badnum + 1 else goodnum = goodnum + 1 end
end
end
@info['bad'] = badnum
@info['good'] = goodnum
end
def getinfo
return @info
end
def getnodes(k=8)
nodes = ""
@@mutex.synchronize do
@@set.each do |k, v|
nodes = nodes + strToHex(k)
info = v.getinfo
ip_int = IPAddr.new(info['host']).to_i
nodes = nodes + [ip_int].pack("i*")
nodes = nodes + [info['port']].pack("s")
end
end
return nodes
end
end