-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
46 lines (38 loc) · 1.47 KB
/
utils.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
from packet import Packet
def parseSenderArgument(args):
listOfSysArg = list(args)
lenSysArg = len(listOfSysArg)
# Check number of arguments
if lenSysArg <= 3: # Notice that the script py file (sender.py) is included
print("Arguments not correct, please input arguments of [path] [address..] [port]")
exit()
# Parse arguments (assumes that is in the correct format)
# Take fileContent
try:
fileContent = str.encode(open(listOfSysArg[1], 'r').read())
except:
print("Error file not found in the specified path")
exit()
# Take server addresses
listOfAddresses = listOfSysArg[2].split(',')
# Take port
port = int(listOfSysArg[-1])
return (fileContent, listOfAddresses, port)
def turnMessageToPackets(msg, maxSize = 32767):
packets = []
it, seq, lenMsg = 0, 0, len(msg)
while it < lenMsg:
# (TYPE, LENGTH, SEQUENCE NUMBER, CHECKSUM, DATA)
newPacket = Packet(b'\x00' if it + maxSize < lenMsg else b'\x02', \
min(lenMsg - it, maxSize), seq, \
msg[it: it + maxSize])
packets += [newPacket]
it, seq = it + maxSize, seq + 1
return packets
def turnRawToPacket(raw):
tipe = int(raw[0]).to_bytes(1, 'big')
length = int.from_bytes(raw[1: 3], 'big')
sequenceNumber = int.from_bytes(raw[3: 5], 'big')
checksum = raw[5: 7]
data = raw[7:]
return Packet(tipe, length, sequenceNumber, data, checksum)