Repository navigation
Expand file tree
/
Copy pathpacketswitching.py
More file actions
70 lines (56 loc) · 2.1 KB
/
Copy pathpacketswitching.py
File metadata and controls
70 lines (56 loc) · 2.1 KB
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
import random
import time
senderPackets = []
receiverPackets = []
r1 = []
r2 = []
message = ""
parity = 0
#input a message to send
message = input("Input a message: ")
#Go through each character of the message and turn it into a packet [header,payload,trailer]
#In each packet we will record the packet number which is the current list length, the character as payload, and the parity 'bit' which is the current length modulus 2 which alternates 0 or 1
for char in message:
#[packet number, payload, parity check]
senderPackets.append([len(senderPackets), char, len(senderPackets)%2])
print("Packets to be sent:", senderPackets)
#send each packet in the senderPackets list
for packet in senderPackets:
#choose a random router to send to
router = random.choice([r1,r2])
#add packet to the router list
print("Packet number", packet[0], "with payload", packet[1], "sent")
router.append(packet)
time.sleep(0.05)
#output the router lists for checking
print("Packets sent through router 1:", r1)
print("Packets sent through router 2:", r2)
#for each packet sent to a router, send it to the receiver
for packet in r1[:]:
print("Packet number", packet[0], "with payload", packet[1], "sent to receiver")
receiverPackets.append(packet)
r1.remove(packet)
for packet in r2[:]:
print("Packet number", packet[0], "with payload", packet[1], "sent to receiver")
receiverPackets.append(packet)
r2.remove(packet)
#output unsorted packets at receiver for checking
print("Unsorted packets received at receiver:")
for packet in receiverPackets:
print(packet)
#this returns the packet number so we can sort
def packetNumber(e):
return e[0]
#sort the packets by the packet number
receiverPackets.sort(key=packetNumber)
receiverMessage = ""
parity = 0
#reconstruct the message and also check for parity in message (should alternate between 1 and 0)
for packet in receiverPackets:
if parity % 2 == packet[2]:
print("Parity check for packet passed!")
parity += 1
receiverMessage += packet[1]
time.sleep(0.05)
print("---------------")
print("Message received:", receiverMessage)