-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_client_consistent.py
60 lines (49 loc) · 1.66 KB
/
cache_client_consistent.py
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
import sys
import socket
from sample_data import USERS
from server_config import NODES
from pickle_hash import serialize_GET, serialize_PUT,serialize_DELETE
from consistent_hash import ConsistentHash
BUFFER_SIZE = 1024
class UDPClient():
def __init__(self, host, port):
self.host = host
self.port = int(port)
def send(self, request):
print('Connecting to server at {}:{}'.format(self.host, self.port))
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(request, (self.host, self.port))
response, ip = s.recvfrom(BUFFER_SIZE)
return response
except socket.error:
print("Error! {}".format(socket.error))
exit()
def process(udp_clients):
client_ring = ConsistentHash(udp_clients)
hash_codes = set()
# PUT all users.
for u in USERS:
data_bytes, key = serialize_PUT(u)
response = client_ring.get_node(key).send(data_bytes)
print(response)
hash_codes.add(str(response.decode()))
print(f"Number of Users={len(USERS)}\nNumber of Users Cached={len(hash_codes)}")
# GET all users.
for hc in hash_codes:
print(hc)
data_bytes, key = serialize_GET(hc)
response = client_ring.get_node(key).send(data_bytes)
print(response)
# DELETE
for hc in hash_codes:
print(hc)
data_bytes, key = serialize_DELETE(hc)
response = client_ring.get_node(key).send(data_bytes)
print(response)
if __name__ == "__main__":
clients = [
UDPClient(server['host'], server['port'])
for server in NODES
]
process(clients)