forked from pskalip/Reliable-UDP-With-Selective-Repeat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
94 lines (78 loc) · 2.45 KB
/
server.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
84
85
86
87
88
89
90
91
92
93
# Rahul R Shevade - 2017B3A70878H
# Kasam Vamshi - 2017B3A70740H
# Shanmukh Kaliprasad Padmanabhuni - 2017B3A71048H
# Pranav V Grandhi - 2017B2A71604H
# Suhas Reddy N - 2017B4A70885H
# Vashist SLN - 2017B3A70381H
import hashlib
from data_packet import *
import socket
import random
global expected_pkt, curr_pkt, pkt_buffer, pkt_list
class server:
def __init__(self, server_IP, server_port):
self.server_IP=server_IP
self.server_port=server_port
self.ack_port= server_port+5
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('', server_port))
self.server_socket=server_socket
ack_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ack_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ack_socket.bind(('', self.ack_port))
self.ack_socket= ack_socket
def receive(self):
global expected_pkt, curr_pkt, pkt_buffer, pkt_list
expected_pkt=0
curr_pkt=-1
pkt_buffer=[]
pkt_list=[]
flag=False
while True:
data, from_address = self.server_socket.recvfrom(1024)
# print(getdict(data))
client_address = (from_address[0],from_address[1]+5)
temp=getdict(data)
# r = random.random()
# if(r<=0.8):
# print("Packet Loss")
# continue
if(checkSumVerification(data)):
ackpkt= createAck(temp['number'])
self.ack_socket.sendto(ackpkt,client_address)
if(temp['number']==expected_pkt):
expected_pkt+=1
curr_pkt=temp["number"]
pkt_list.append(data)
while pkt_buffer and pkt_buffer[0]==expected_pkt:
curr_pkt=expected_pkt
expected_pkt+=1
pkt_buffer.remove(pkt_buffer[0])
pkt_buffer.sort()
elif( temp['number']>expected_pkt and temp['number'] not in pkt_buffer):
pkt_list.append(data)
pkt_buffer.append(temp['number'])
pkt_buffer.sort()
for pkt in pkt_list:
temp= getdict(pkt)
if(temp['number']==curr_pkt):
if(temp['pkt_type']=='close_pkt'):
flag=True
break
if flag:
break
for i in range(len(pkt_list)):
temp=getdict(pkt_list[i])
pkt_list[i]=temp
final_data_list = sorted(pkt_list,key=lambda k: k['number'])
for pkt in final_data_list:
if(pkt["pkt_type"]=="file_pkt"):
filename="output_"+bytes(pkt['data']).decode('utf-8')
break
fd=open(filename,"wb")
for pkt in final_data_list:
# print("hey",pkt)
if(pkt["pkt_type"]=="data_pkt"):
fd.write(bytes(pkt['data']))
# close(filename)