def send_file(self): udp_socket = socket(AF_INET, SOCK_DGRAM) while True: if self.get_timer() > self.MAX_DELAY: #print("timer timeout: " + str(self.get_timer())) self.lock_window.acquire() for pkt in self.window: udp_socket.sendto(pkt.get_udp_data(), (self.host_address, self.udp_port_data)) #print("timeout pkt: seqnum " + str(pkt.seq_num)) self.log_sent(str(pkt.seq_num)) self.set_timer() self.lock_window.release() #if window is not full, load new packet self.lock_window.acquire() if len(self.window) < self.WINDOW_SIZE: """ #after all pkt 0-31 has been sent, wait for all of then be acked if len(self.window) != 0 and self.get_next_seqnum() == 0: self.lock_window.release() continue """ self.lock_window.release() data = self.get_next_filedata() if data == "": #file has been completely read and #all the packet in window has sent self.lock_window.acquire() if len(self.window) == 0: self.lock_window.release() #send eot #print("pkt: eot seq_num " + str(self.get_next_seqnum())) packet_to_send = packet.create_eot(self.get_next_seqnum()) udp_socket.sendto(packet_to_send.get_udp_data(), (self.host_address, self.udp_port_data)) udp_socket.close() break else: self.lock_window.release() #create new pkt and send it elif data != "": packet_to_send = packet.create_packet(self.get_next_seqnum(), data) self.lock_window.acquire() #print("pkt: seq_num " + str(self.get_next_seqnum())) #print(self.window) udp_socket.sendto(packet_to_send.get_udp_data(), (self.host_address, self.udp_port_data)) self.log_sent(str(packet_to_send.seq_num)) #set timer if the pkt is the only pkt sent but not acked if len(self.window) == 0: self.set_timer() self.window.append(packet_to_send) self.next_seqnum += 1 self.lock_window.release() else: self.lock_window.release()
def file_to_pkt(self, file_name): # print("begin to convert all the file into packet-----------") data_file = open(file_name, 'r') data = data_file.read(DATA_LENGTH) while data: self.pkt_list.append(packet.create_packet(self.NUM_PKT, data)) self.NUM_PKT += 1 data = data_file.read(DATA_LENGTH) # print("begin to packet EOT ---------------------") eot = packet.create_eot(self.NUM_PKT) self.pkt_list.append(eot) self.NUM_PKT += 1
def resend_all(self, addr: Tuple[str, int]): """ Resends all data in the window. Args: addr: A hostname, port tuple to send data to. """ for num, data in zip(range(constants.MODULO_RANGE), self.window): if data: self._logger.sequence(num) socket(AF_INET, SOCK_DGRAM).sendto( packet.create_packet(num, data).get_udp_data(), addr) self._logger.log(f"Resent packet with no: {num}") self.reset_timer()
def main(commandlineArgs): # check if correct number of arguments is supplied if not len(commandlineArgs) == 5: print('Error: the number of parameter supplied is incorrect') sys.exit(2) hostAddr = commandlineArgs[1] hostPort = int(commandlineArgs[2]) ackPort = int(commandlineArgs[3]) fileName = commandlineArgs[4] # open and prepare files fileToBeSent = open(fileName, 'r') seqNumLog = open('seqnum.log', 'w+') ackLog = open('ack.log', 'w+') # clear the content of log files before writing seqNumLog.write('') ackLog.write('') seqNumLog.close() ackLog.close() # read to-be-sent file content to a variable if fileToBeSent.mode == 'r': fileContent = fileToBeSent.read() else: print('Error: cannot open file to be sent') sys.exit(3) # calculate the number of packets needed to send the file numOfPkgs = len(fileContent) // 500 if len(fileContent) % 500 > 0: numOfPkgs += 1 pkgList = [] # create a list of packets to be sent for i in range(0, numOfPkgs): if i == numOfPkgs - 1: start = i * 500 end = len(fileContent) else: offset = i * 500 start = 0 + offset end = 500 + offset newPkg = packet.create_packet(i, fileContent[start:end]) pkgList.append(newPkg) # send the packets using the sending function sendPackages(pkgList, hostAddr, hostPort, ackPort) sys.exit(0)
def fileToPacket(filename): global NUM_OF_PACKETS packets = [] file = open(filename, "rb").read().decode() NUM_OF_PACKETS = math.ceil( len(file) / DATA_SIZE) + 1 # all data packets + 1 EOT packet for i in range(0, NUM_OF_PACKETS - 1): data = file[i * DATA_SIZE:min((i + 1) * DATA_SIZE, len(file))] packets.append(packet.create_packet(i, str(data))) # in bytes packets.append(packet.create_eot(NUM_OF_PACKETS - 1)) # last packet is the EOT packet return packets
def add_data(self, data: str, addr: Tuple[str, int]): """ Adds and sends data to the window in the next available slot. Args: data: The data to be added in the window slot, expected to be fixed-size bytes. addr: A hostname, port tuple to send data to. """ socket(AF_INET, SOCK_DGRAM).sendto( packet.create_packet(self.seq_number, data).get_udp_data(), addr) self._logger.sequence(self.seq_number) self._logger.log(f"Sent packet with no: {self.seq_number}") self.window[self.seq_number] = data self.seq_number = (self.seq_number + 1) % constants.MODULO_RANGE
def __init__(self, host_addr, emulator_port, sender_port, data_file_path): self.packets_list = list() self.host_addr = host_addr self.emulator_port = emulator_port self.sender_port = sender_port self.lock = threading.Lock() self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.udp_socket.bind(('', sender_port)) self.next_ack = 0 self.seqnum_log = list() self.time_log = list() self.ack_log = list() self.seqnum_log_file = open('seqnum.log', 'w') self.ack_log_file = open('ack.log', 'w') self.time_log_file = open('time.log', 'w') seq_num = 0 with open(data_file_path, 'r') as f: chunk = f.read(self.MAX_DATA_LENGTH) while chunk: self.packets_list.append(packet.create_packet(seq_num, chunk)) seq_num += 1 chunk = f.read(self.MAX_DATA_LENGTH) # self.packets_list.append(packet.create_eot(seq_num)) print("Number of data packets is: " + str(len(self.packets_list))) # Initlialize the sliding window self.sliding_window = list() if len(self.packets_list) < self.WINDOW_SIZE: self.sliding_window.extend(self.packets_list) else: self.sliding_window.extend(self.packets_list[:self.WINDOW_SIZE]) self.packets_list = self.packets_list[self.WINDOW_SIZE:]
def RdtSend(EmulatorHostAddress, EmulatorPortNumRecFrSender, FileNameToTrans): signal.signal(signal.SIGALRM, resend) #divide the data bytes array into packets, each with 500 bytes data FileByteBuffer = read_into_buffer(FileNameToTrans) Num_Of_Packets = int(math.ceil(len(FileByteBuffer) / 500)) #send use UDP global SenderSendSocket SenderSendSocket = socket(AF_INET, SOCK_DGRAM) seq_num = 0 for i in range(Num_Of_Packets): if ((i != (Num_Of_Packets - 1)) and check_if_can_send()): if (len(SeqNumSentNotAck) == 0): #start the timer when the window is empty and begin start sending packet signal.setitimer(signal.ITIMER_REAL, Timeout) # 500 bytes data for the packet data field message = FileByteBuffer[(i * 500):((i * 500) + 500)] Message_Packet = packet.create_packet(seq_num, message.decode()) seq_num_to_write = "{}{}".format(Message_Packet.seq_num, '\n') seq_num_log.write(seq_num_to_write) SeqNumSentNotAck.append(Message_Packet.seq_num) PacketSentNotAck.append(Message_Packet) SeqNumSent.append(Message_Packet.seq_num) SenderSendSocket.sendto( Message_Packet.get_udp_data(), (EmulatorHostAddress, EmulatorPortNumRecFrSender)) seq_num += 1 continue else: #send the last packet data of the source file message = FileByteBuffer[(i * 500):len(FileByteBuffer)] Message_Packet = packet.create_packet(seq_num, message.decode()) seq_num_to_write = "{}{}".format(Message_Packet.seq_num, '\n') seq_num_log.write(seq_num_to_write) SeqNumSentNotAck.append(Message_Packet.seq_num) PacketSentNotAck.append(Message_Packet) SeqNumSent.append(Message_Packet.seq_num) SenderSendSocket.sendto( Message_Packet.get_udp_data(), (EmulatorHostAddress, EmulatorPortNumRecFrSender)) # every 0.1 seconds to check if the sender has transimit successfully and acked all the ack while (len(SeqNumSentNotAck) != 0): time.sleep(0.1) # send EOT seq_num += 1 EOT_Packet = packet.create_eot(seq_num) SenderSendSocket.sendto(EOT_Packet.get_udp_data(), (EmulatorHostAddress, EmulatorPortNumRecFrSender)) SeqNumSent.append(EOT_Packet.seq_num) # wait the sender receiving socket to close and the EOT will not lose in the internet so i choose 1 second # only receive the EOT ack from receiver, the sender can close the sending socket time.sleep(1) SenderSendSocket.close()
def main(args): # Call global constant global max_packet_length # Check the number of arguments is correct or not if not len(args) == 5: print('Error 2: expected 5 arguments, %d was received' % (len(args))) sys.exit(2) # Check if the type of argument is correct if (not ((args[2]).isdigit())) or (not ((args[3]).isdigit())): print('Error 4: port number must be an integer') sys.exit(4) # Get arguments naddr = args[1] host_port = int(args[2]) ACK_port = int(args[3]) file_name = args[4] # Open and prepare files sfile = open(file_name, 'r') seqnum_log = open('seqnum.log', 'w+') ACK_log = open('ack.log', 'w+') # Make sure the log file is empty seqnum_log.write('') ACK_log.write('') seqnum_log.close() ACK_log.close() # Read send file content if sfile.mode == 'r': fileContent = sfile.read() else: print('Error: file permission denied') sys.exit(3) # Calculate the number of packets needed num_pkts = (len(fileContent)) // max_packet_length if len(fileContent) % max_packet_length > 0: num_pkts += 1 # Create the packet window pkts = [] # Save the packet to the list for i in range(0, num_pkts): if i == (num_pkts - 1): start = i * max_packet_length end = len(fileContent) else: offset = i * max_packet_length start = 0 + offset end = max_packet_length + offset newPkg = packet.create_packet(i, fileContent[start:end]) pkts.append(newPkg) # Send the packets packets_sender(pkts, naddr, host_port, ACK_port) sys.exit(0)
# command line hostAddress = sys.argv[1] sendDataPort = int(sys.argv[2]) receiveAckPort = int(sys.argv[3]) filename = sys.argv[4] # read file data with open(filename) as f: data = f.read() packets = [] for p in range(0, len(data), packet.MAX_DATA_LENGTH): packets.append( packet.create_packet(int(p / packet.MAX_DATA_LENGTH), data[p:(p + packet.MAX_DATA_LENGTH)])) N = 10 # window size packetsSent = 0 totalPackets = len(packets) # UPD socket senderSocket = socket(AF_INET, SOCK_DGRAM) senderSocket.bind((hostAddress, receiveAckPort)) while packetsSent < totalPackets: # set endpoint to loop until min(packetsSent + N, totalPackets), start new thread for current window startpoint = packetsSent endpoint = min(packetsSent + N, totalPackets) acknowledger = threading.Thread(target=ack, args=(startpoint, endpoint))
def main(): #get arguments emulator_hostname = sys.argv[1] emulator_port = sys.argv[2] sender_port = sys.argv[3] transfer_file = sys.argv[4] #create packets sequence_number = 0 file_transfer = open(transfer_file, "r") pos = 0 data_file = file_transfer.read() filesize = len(data_file) numloop = filesize // 500 + 1 for x in range(numloop): if x == numloop - 1: data = data_file[pos:] packet_cur = packet.create_packet(sequence_number, data) packets.append(packet_cur) else: data = data_file[pos:pos + 500] packet_cur = packet.create_packet(sequence_number, data) packets.append(packet_cur) sequence_number += 1 pos = pos + 500 #clean output file open("time.log", "w").close() open("ack.log", "w").close() open("seqnum.log", "w").close() #create udp connection to emulator udpSocket = socket(AF_INET, SOCK_DGRAM) udpSocket.bind(('', int(sender_port))) #set up multithread thread_send = myThread("send", udpSocket, emulator_hostname, emulator_port, sender_port) thread_receive = myThread("receive", udpSocket, emulator_hostname, emulator_port, sender_port) thread_send.start() thread_receive.start() threads = [] threads.append(thread_send) threads.append(thread_receive) for t in threads: t.join() udpSocket.close() #write into time.log file_time = open("time.log", "a") file_time.write(str(end_time * 1000 - start_time * 1000)) file_time.close() # print("end_time: ", end_time) # print("start_time: ", start_time) print("transmission time: ", end_time * 1000 - start_time * 1000) sys.exit()