-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdirectory.py
43 lines (35 loc) · 1.04 KB
/
directory.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
import socket
import pickle
PORT = 9001
SERVER = 'localhost'
ROUTERS = {}
def listen():
ssocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssocket.bind((SERVER, PORT))
ssocket.listen()
print('Directory is listening on {}:{}'.format(SERVER, PORT))
while True:
connection, address = ssocket.accept()
print('New connection from {}'.format(address))
# recv message
msg = connection.recv(4096)
cmd = msg[0:1]
if cmd == b'R':
data = msg[1:]
obj = pickle.loads(data)
addr = '{}:{}'.format(obj['ip'], obj['port'])
pubKey = obj['pubKey']
# save router info
ROUTERS.update({addr:pubKey})
print('Router {} registered'.format(addr))
elif cmd == b'G':
data = pickle.dumps(ROUTERS)
connection.send(data)
print('{} fetched routers'.format(address))
connection.close()
return
def main():
listen()
return None
if __name__ == '__main__':
main()