def rec(self, recv_window): #if self.connection_status != Status.IDLE: # raise CRPException("Status is not idle!") resends_rem = self.resend_limit while resends_rem > 0: try: self.socket.settimeout(5) recv_data, recv_addr = self.recv_packet(self.recv_window) except socket.timeout: resends_rem -= 1 continue else: recv_pckt = CRPPacket(packet=recv_data) if recv_pckt.calc_checksum() == recv_pckt.checksum and recv_pckt.data != str(None) \ and self.connection_status == Status.CONNECTED: print (recv_pckt.data) self.send_ACK() elif recv_pckt.calc_checksum() != recv_pckt.checksum: raise CRPException(CRPException.CHECKSUM_INVALID) if recv_pckt.FIN and not recv_pckt.ACK: self.send_FINACK() print("Disconnected from Client.") self.connection_status = Status.LISTEN return (recv_data, recv_addr) else: return (recv_data, recv_addr) if resend_rem == 0: raise CRPException(CRPException.TIMEOUT)
def send_FINACK(self): fin_ack_pckt = CRPPacket(src_port=self.src_addr[1], dest_pstevejobsort=self.dest_addr[1], \ seq_num=self.sequence_num, ack_num=self.ack_num) fin_ack_pckt.FIN = 1 fin_ack_pckt.ACK = 1 self.sequence_num += 1 resends_rem = self.resend_limit recv_pckt = None while resends_rem > 0: self.send_packet(fin_ack_pckt.get_packet()) try: recv_data, recv_addr = self.rec(self.recv_window) recv_pckt = CRPPacket(packet=recv_data) except CRPException as exception: if (exception.type == CRPException.CHECKSUM_INVALID): continue else: if recv_pckt != None and recv_pckt.ACK: break elif recv_pckt != None and recv_pckt.FIN: resends_rem = self.resend_limit if resends_rem == 0: raise CRPException(CRPException.TIMEOUT)
def send_SYN(self): syn_pckt = CRPPacket(src_port=self.src_addr[1], dest_port=self.dest_addr[1], seq_num=self.sequence_num) syn_pckt.SYN = 1 self.sequence_num += 1 resends_rem = self.resend_limit recv_pckt = None while resends_rem > 0: self.send_packet(syn_pckt.get_packet()) try: recv_data, recv_addr = self.rec(self.recv_window) recv_pckt = CRPPacket(packet=recv_data) except CRPException as exception: if (exception.type == CRPException.CHECKSUM_INVALID): continue else: if recv_pckt != None and recv_pckt.SYN and recv_pckt.ACK: break if resends_rem == 0: raise CRPException(CRPException.TIMEOUT) return recv_pckt
def listen(self): self.connection_status = Status.LISTEN recv_pckt = None while True: try: recv_data, recv_addr = self.rec(self.recv_window) recv_pckt = CRPPacket(packet=recv_data) except CRPException as exception: if (exception.type == CRPException.CHECKSUM_INVALID): continue else: if recv_pckt != None and recv_pckt.SYN: break self.ack_num = int(recv_pckt.seq_num) + 1 self.dest_addr = recv_addr
def send_ACK(self): ack_pckt = CRPPacket(src_port=self.src_addr[1], dest_port=self.dest_addr[1], ack_num=self.ack_num) ack_pckt.ACK = 1 self.send_packet(ack_pckt.get_packet())