def send_packet(self, packet, client): seq_num = packet.__get__('seq_num') client_timeout_count = CLIENT_TIMEOUT_TRIALS while client_timeout_count: if randint(1, 100) > LOSS_PROBABILITY: client.send(packet.__dumb__()) else: print(colored('Simulating Packet Loss: ' + seq_num, 'red')) try: # Wait for response or timeout res = client.recv(PACKET_SIZE) if not res: print('Client Disconnected') return 0 pkt = Packet(pickled=res) pkt.__print__() if pkt.__get__('ack') == '+': return 1 else: print(colored('Negative ack, resending : ' + seq_num, color='red')) except timeout: print(colored('Timeout, resending packet: ' + seq_num, color='red')) client_timeout_count -= 1 return 0
def wait_for_request(self, client, address): client_timeout_count = CLIENT_TIMEOUT_TRIALS while client_timeout_count: try: request = client.recv(PACKET_SIZE) if request: pkt = Packet(pickled=request) pkt.__print__() return pkt else: print('Client disconnected, address:', address) break except timeout: client_timeout_count -= 1 return 0
def begin_transimission(self, packets, client, address): base = 0 self.send_window(packets, base, client, address) client_timeout_count = CLIENT_TIMEOUT_TRIALS while client_timeout_count: if base >= len(packets): break end = base + WINDOW_SIZE end = end if end < len(packets) else len(packets) client.settimeout(TIME_OUT_SEC) try: # Wait for response or timeout res = client.recv(PACKET_SIZE) if not res: break pkt = Packet(res=res) pkt.__print__(from_address=address) seq_num = int(pkt.__get__('seq_num')) if base <= seq_num <= base + WINDOW_SIZE: if pkt.__get__('ack') == '+': client.settimeout(None) free_slots = int(pkt.__get__('seq_num')) - base + 1 nEnd = end + free_slots nEnd = nEnd if nEnd < len(packets) else len(packets) new_pkts = packets[end:nEnd] for pkt in new_pkts: if randint(1, 100) > LOSS_PROBABILITY: pkt.__print__(to_address=address) client.send(pkt.__dump__()) else: print(colored('Simulating Packet Loss: ' + pkt.__get__('seq_num'), 'red')) base += free_slots else: print(colored('Ack out of window, discard ' + str(seq_num) + ' => from: ' + str(address), color='blue')) except timeout: print(colored('Timeout, resending window. => to: ' + str(address), color='red')) self.send_window(packets, base, client, address) client_timeout_count -= 1 # Retrun number of timeouts return CLIENT_TIMEOUT_TRIALS - client_timeout_count