forked from rasa97/peqi-ot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
communication.py
54 lines (47 loc) · 1.56 KB
/
communication.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
# def send_message(sender, receiver, message):
# sender.sendClassical(receiver, message)
# res = sender.recvClassical()
# assert res == b'ACK'
# def receive_message(receiver, sender):
# msg = receiver.recvClassical()
# receiver.sendClassical(sender, b'ACK')
# return msg
import pickle
import socket
def _send_message(sender, receiver_name, msg):
# print(sender, receiver_name, msg)
socket_info = sender._appNet.getStateFor(sender.name)['hostDict'][receiver_name]
s = socket.socket()
while True:
try:
s.connect((socket_info.hostname, socket_info.port))
break
except Exception as e:
continue
s.send(pickle.dumps(len(msg)))
ack = s.recv(32)
bytes_sent = 0
while bytes_sent < len(msg):
bytes_sent += s.send(msg[bytes_sent:])
ack = s.recv(32)
s.close()
def receive_message(receiver,_):
socket_info = receiver._appNet.getStateFor(receiver.name)['hostDict'][receiver.name]
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((socket_info.hostname, socket_info.port))
s.listen(1)
c, addr = s.accept()
len_msg = pickle.loads(c.recv(256)) #.decode('utf-8')
c.send('ACK'.encode('UTF-8'))
msg = b''
while len(msg) < len_msg:
msg += c.recv(4096)
c.send('ACK'.encode('UTF-8'))
c.close()
s.close()
return msg
def send_message(sender, receiver_name, msg):
_send_message(sender, receiver_name, bytes(msg))
# def receive_message(receiver):
# return list(_receive_message(receiver))