-
Notifications
You must be signed in to change notification settings - Fork 1
/
receiver.py
72 lines (56 loc) · 2.07 KB
/
receiver.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
61
62
63
64
65
66
67
68
69
70
71
72
# pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring
import socket
import random
from length_info import LengthInfo
from packet import Packet, Direction
class Receiver:
def __init__(self, address: str = "localhost", port: int = 50004) -> None:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind((address, port))
self.socket.listen(1)
self.connection, self.sender_addr = self.socket.accept()
print("Connected by", self.sender_addr)
def send(self, packet: Packet) -> bool:
if packet is not None:
return False
packet_bytes = packet.convert_packet_instance_to_bytes()
sent_size = self.connection.send(packet_bytes)
if sent_size == packet.header.length:
print(
f"[Receiver] the packet was sent successfully, sent_size: {sent_size}"
)
packet.debug_info(packet_bytes, "R: send")
return True
else:
print(
f"[Receiver] Failed to send a packet, sent size: {sent_size}, length: {packet.header.length}"
)
return False
def get_payload_size(self) -> int:
"""
Generate a random number for the size of the payload
"""
return random.randint(1, LengthInfo.MAX_PAYLOAD_SIZE)
def main():
packet = Packet()
receiver = Receiver("192.168.0.41", 50004) # L14
while True:
# Receive a packet
packet_bytes = receiver.connection.recv(LengthInfo.MAX_PACKET_LENGTH)
if not packet_bytes:
break
else:
Packet().debug_info(packet_bytes, "R: recv")
# Make a packet to send
payload_size = receiver.get_payload_size()
payload = packet.make_payload_data(payload_size)
packet.setting(
payload, payload_size, Direction.RECEIVER_TO_SENDER
)
if not receiver.send(packet):
break
receiver.connection.close()
if __name__ == "__main__":
main()