-
Notifications
You must be signed in to change notification settings - Fork 0
/
Receiver.py
83 lines (59 loc) · 1.76 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
73
74
75
76
77
78
79
80
81
82
83
from socket import *
import pickle
class Packet:
def __init__(self, seq_number, last_ack, payload):
self.seq_number = seq_number
self.last_ack = last_ack
self.payload = payload
IP = '127.0.0.1'
PORT = 54321
DEST_IP = '127.0.0.1'
DEST_PORT = 5080
receiver_socket = None
sender_socket = None
state = 0
packet = None
def creating_response(ack_number):
return Packet(seq_number=0, last_ack=ack_number, payload='')
def sending_response(ack_number, sender_address):
response = creating_response(ack_number)
response_packet = pickle.dumps(response)
receiver_socket.sendto(response_packet, sender_address)
def transfer_payload():
global packet
transfer_packet = bytes(packet.payload, encoding='utf8')
transfer_address = (DEST_IP, DEST_PORT)
sender_socket.sendto(transfer_packet, transfer_address)
def state_1_handler(data, addr):
global packet
global state
packet = pickle.loads(data)
if packet.seq_number == 0:
sending_response(0, addr)
else:
transfer_payload()
sending_response(1, addr)
state = 0
def state_0_handler(data, addr):
global state
global packet
packet = pickle.loads(data)
if packet.seq_number == 1:
sending_response(1, addr)
else:
transfer_payload()
sending_response(0, addr)
state = 1
def receiving_packets():
global state
while True:
data, addr = receiver_socket.recvfrom(4096)
if state == 0:
state_0_handler(data, addr)
elif state == 1:
state_1_handler(data, addr)
if __name__ == '__main__':
receiver_socket = socket(AF_INET, SOCK_DGRAM)
receiver_socket.bind((IP, PORT))
sender_socket = socket(AF_INET, SOCK_DGRAM)
receiving_packets()