def receive(self, emulator_addr, emulator_port): # print("begin to receive -----------------") while True: rcv_data, address = self.rcv_udp_socket.recvfrom(1024) # print("receive a new packet ------------------") rcv_packet = packet.parse_udp_data(rcv_data) # print("receive pkt seq_num" + str(rcv_packet.seq_num)) expected_num = self.expected_seq_num % SEQ_NUM_MODULO if rcv_packet.seq_num == expected_num: if rcv_packet.type == 2: # print("receive all data and begin to send EOT -----------------------") msg = packet.create_eot(rcv_packet.seq_num).get_udp_data() self.send_udp_socket.sendto(msg, (emulator_addr, emulator_port)) self.send_udp_socket.close() self.rcv_udp_socket.close() break elif rcv_packet.type == 1: self.expected_seq_num += 1 self.data_list.append(rcv_packet.data) self.arrival_log.append(rcv_packet.seq_num) if self.expected_seq_num != 0: # print("begin to send ACK ------------------") cur_ack_num = (self.expected_seq_num - 1) % SEQ_NUM_MODULO # print("send ack" + str(cur_ack_num)) ack_msg = packet.create_ack(cur_ack_num).get_udp_data() self.send_udp_socket.sendto(ack_msg, (emulator_addr, emulator_port))
def send_EOT(self, seq_num): """ Sends an EOT packet. """ socket(AF_INET, SOCK_DGRAM).sendto( packet.create_eot(seq_num).get_udp_data(), (self.hostname, self.data_port)) logger.log(f"Sent EOT with: {seq_num}.")
def RecSendAck(EmulatorHostName, EmulatorPortNumAckFrRec, RecPortNumRecDataFroE, FileNameToWriteData): receiverSocket = socket(AF_INET, SOCK_DGRAM) receiverSocket.bind(('', RecPortNumRecDataFroE)) while True: packet_rec_udp, clientAddress = receiverSocket.recvfrom(2048) # parse the recieved packet packet_rec = packet.parse_udp_data(packet_rec_udp) seq_num_rec = packet_rec.seq_num # if the packet is not EOT, record in the arrival log if (packet_rec.type != 2): arrival_to_write = "{}{}".format(seq_num_rec, '\n') arrival_log.write(arrival_to_write) # deal with the first packet's seq num is not the seq num = 0 situation if (len(rec_seq_num) == 0 and seq_num_rec != 0): continue # receive the first expected packet if (len(rec_seq_num) == 0): rec_seq_num.append(seq_num_rec) Ack_packet = packet.create_ack(seq_num_rec) f.write(packet_rec.data) receiverSocket.sendto(Ack_packet.get_udp_data(), (EmulatorHostName, EmulatorPortNumAckFrRec)) continue #receive the EOT packet if ((packet_rec.type == 2)): EOT_packet = packet.create_eot(seq_num_rec) receiverSocket.sendto(EOT_packet.get_udp_data(), (EmulatorHostName, EmulatorPortNumAckFrRec)) arrival_log.close() receiverSocket.close() f.close() break #not receive the expected packet if (seq_num_rec != (((rec_seq_num[len(rec_seq_num) - 1] + 1) % SEQ_NUM_MODULO))): Ack_packet = packet.create_ack(rec_seq_num[len(rec_seq_num) - 1]) receiverSocket.sendto(Ack_packet.get_udp_data(), (EmulatorHostName, EmulatorPortNumAckFrRec)) continue #receive the expected packet if (seq_num_rec == (((rec_seq_num[len(rec_seq_num) - 1] + 1) % SEQ_NUM_MODULO))): rec_seq_num.append(seq_num_rec) Ack_packet = packet.create_ack(seq_num_rec) f.write(packet_rec.data) receiverSocket.sendto(Ack_packet.get_udp_data(), (EmulatorHostName, EmulatorPortNumAckFrRec)) continue
def receive(filename, emulatorAddr, emuReceiveACK, client_udp_sock): global expected_pkt_num save_data = bytearray() try: file = open(filename, 'wb') except IOError: print('Unable to open', filename) return while True: msg, _ = client_udp_sock.recvfrom(4096) data_packet = packet.parse_udp_data(msg) packet_type = data_packet.type seq_num = data_packet.seq_num data = data_packet.data arrival_log.append(seq_num) # receives EOT, send EOT back and exit if packet_type == 2 and seq_num == expected_pkt_num % SEQ_MODULO: client_udp_sock.sendto(packet.create_eot(seq_num).get_udp_data(), (emulatorAddr, emuReceiveACK)) break # receives expected data packet if seq_num == expected_pkt_num % SEQ_MODULO: expected_pkt_num += 1 save_data.extend(data.encode()) # if the very first data packet #0 get lost, do not ACK and wait for a timeout resend. if expected_pkt_num != 0: ack_num = (expected_pkt_num - 1) % SEQ_MODULO client_udp_sock.sendto(packet.create_ack(ack_num).get_udp_data(), (emulatorAddr, emuReceiveACK)) file.write(save_data) file.close()
def send(udpSocket, emulator_hostname, emulator_port): x_counter = 0 num_packets = len(packets) firstFlag = True global window_location sequence_number = 0 while True: if timer.started == True and timer.check_timer() == True: resend(udpSocket, emulator_hostname, emulator_port) # print("after resend: ", window_states) # print_window_seq_num() timer.start_timer() if window_location == num_packets: # print("before send eot") sequence_number += 1 packet_eot = packet.create_eot(sequence_number) packet_eot_encode = packet_eot.get_udp_data() udpSocket.sendto(packet_eot_encode, (emulator_hostname, int(emulator_port))) file_seqnum = open("seqnum.log", "a") file_seqnum.write(str(packet_eot.seq_num) + "\n") file_seqnum.close() break window_lock.acquire() current_window_size = len(window) if current_window_size < 10 and x_counter < num_packets: if firstFlag == True: global start_time start_time = time.time() firstFlag = False packet_to_send = packets[x_counter] # print("sender send: " + str(packet_to_send.seq_num)) sequence_number = packet_to_send.seq_num window.append(packet_to_send) window_states.append(0) packet_to_send_encode = packet_to_send.get_udp_data() udpSocket.sendto(packet_to_send_encode, (emulator_hostname, int(emulator_port))) window_states[len(window_states) - 1] = 1 # print("after send:", window_states) # print_window_seq_num() x_counter += 1 if timer.started == False: timer.start_timer() #write into seqnum.log file_seqnum = open("seqnum.log", "a") file_seqnum.write(str(packet_to_send.seq_num) + "\n") file_seqnum.close() window_lock.release()
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 run(self): udp_socket_receive = socket(AF_INET, SOCK_DGRAM) udp_socket_receive.bind(('', self.udp_port_data)) udp_socket_send = socket(AF_INET, SOCK_DGRAM) while True: #print("waitting...") row_data, clientAddress = udp_socket_receive.recvfrom( 1024) #1024 if buffer size received_packet = packet.parse_udp_data(row_data) #print("except seqnum: " + str(self.get_expect_squnum())) #print("actual seqnum: " + str(received_packet.seq_num)) #print(received_packet.data) if received_packet.type == 1: self.log(str(received_packet.seq_num)) if (received_packet.seq_num == self.get_expect_squnum()): self.expect_seqnum += 1 if received_packet.type == 1: if (self.expect_seqnum - 1) == 0: with open(self.file_to_write, "w+") as f: f.write(received_packet.data) else: with open(self.file_to_write, "a") as f: f.write(received_packet.data) #last acked pkt's seqnum is excepted next seqnum - 1 packet_to_send = packet.create_ack( self.get_expect_squnum() - 1) #print("send ack: "+ str(packet_to_send.seq_num)) udp_socket_send.sendto( packet_to_send.get_udp_data(), (self.host_address, self.udp_port_ack)) else: #if the last pkt is not what we want, #resend the lastest acked seqnum #last acked pkt's seqnum is excepted next seqnum - 1 if self.expect_seqnum != 0: packet_to_send = packet.create_ack( self.get_expect_squnum() - 1) #print("send previous ack: "+ str(packet_to_send.seq_num)) udp_socket_send.sendto( packet_to_send.get_udp_data(), (self.host_address, self.udp_port_ack)) elif received_packet.type == 2: packet_to_send = packet.create_eot(self.get_expect_squnum()) udp_socket_send.sendto(packet_to_send.get_udp_data(), (self.host_address, self.udp_port_ack)) #print("eot seqnum: " + str(packet_to_send.seq_num)) udp_socket_send.close() break
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 main(args): # 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]) file_port = int(args[3]) file_name = args[4] # Open files file = open(file_name, 'w+') Arrive_log = open('arrival.log', 'w+') # Create receiving packet receiver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) receiver_socket.bind(('', file_port)) # Define useful variables next_seqnum = 0 counter = 0 first = True # Start receving packets while True: try: data_pkt = receiver_socket.recv(1024) except: print('Error: paeket error') sys.exit(2) # Process received packet data_packet = packet.parse_udp_data(data_pkt) # Recevied packet is file data if data_packet.type == 1: # Record received packet sequence number Arrive_log.write('%d\n' % data_packet.seq_num) # Update expected sequence number and write data to file if the sequence is expected if data_packet.seq_num == next_seqnum: file.write(data_packet.data) next_seqnum += 1 next_seqnum = next_seqnum % packet.SEQ_NUM_MODULO ACK_pkt = packet.create_ack(data_packet.seq_num) first = False # Otherwise, ignore and resend the last/duplicate ACK else: last_ACK_seqnum = next_seqnum - 1 if (last_ACK_seqnum < 0): last_ACK_seqnum = 31 ACK_pkt = packet.create_ack(last_ACK_seqnum) # Stop sending any ACK if it is first time and sequence number is not expected if not first: receiver_socket.sendto(ACK_pkt.get_udp_data(), (naddr, host_port)) counter += 1 # Recevied packet is EOT elif data_packet.type == 2: receiver_socket.sendto( packet.create_eot(next_seqnum - 1).get_udp_data(), (naddr, host_port)) sys.exit(0) # Close files file.close() Arrive_log.close()
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 sendPackages(pkgList, addr, port, recvPort): global lastAckSeqNum global lastAckChanged global noMoreAck # create sender socket sSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sSocket.bind(('', 0)) baseSeqNum = 0 baseIdxNum = 0 currentPkgIdx = 0 # create new thread for ack receiver, pass in function and receiver port receiver = threading.Thread(target=genACKReceiver, args=(recvPort, )) receiver.daemon = True receiver.start() firstRun = True pause = False # start looping through all packets while baseIdxNum < len(pkgList): # check if new ack is received, # update timer and new base sequence number accordingly seqNumLock.acquire() if lastAckChanged: lastAckChanged = False newBase = lastAckSeqNum + 1 diff = newBase - baseSeqNum if diff < 0: diff += 32 if newBase > 31: newBase -= 32 baseIdxNum += diff baseSeqNum = newBase packageTimerStart = getMiliTime() seqNumLock.release() # initialize timer for first run if firstRun: packageTimerStart = getMiliTime() firstRun = False # check if the timer is expired, # update timer if timeout happens, # reset current sending packet to the base if (getMiliTime() - packageTimerStart) > 100: # print('timeout') currentPkgIdx = baseIdxNum packageTimerStart = getMiliTime() pause = False # send packets to the specified port if not pause: sSocket.sendto(pkgList[currentPkgIdx].get_udp_data(), (addr, port)) # write all sent packet to the log file with open('seqnum.log', 'a+') as file: file.write("%d\n" % pkgList[currentPkgIdx].seq_num) file.close() # check if packet window limit is reached or all packets are sent, # wait for window update if window limit is reached currentPkgIdx += 1 if currentPkgIdx < baseIdxNum + 10 and currentPkgIdx < len(pkgList): pause = False else: pause = True # all packets are sent and all acks are received # inform ack receiver thread to exit, send eot packet noMoreAckLock.acquire() noMoreAck = True noMoreAckLock.release() eotPkg = packet.create_eot(len(pkgList) - 1) sSocket.sendto(eotPkg.get_udp_data(), (addr, port)) receiver.join() return
def send(self): cur_ack = 0 foo = 0 start_time = time.time() pack_sent = 0 # how many pack in the sliding window are sent self.time_log.append(time.time()) for pack in self.sliding_window: self.udp_socket.sendto(pack.get_udp_data(), (self.host_addr, self.emulator_port)) pack_sent += 1 self.seqnum_log.append(pack.seq_num) while len(self.sliding_window) != 0 or len(self.packets_list) != 0: while time.time() - start_time < self.TIMEOUT: if cur_ack != self.next_ack: start_time = time.time() self.lock.acquire() print('move_window', 'cur_ack=', cur_ack, ' ', ' next_ack=', self.next_ack, ' pack_sent=', pack_sent) for _ in range( (self.next_ack - cur_ack) % self.SEQ_NUM_MODULO): self.sliding_window.pop(0) pack_sent -= 1 # print('pack_sent -= 1') if len(self.packets_list) != 0: self.sliding_window.append( self.packets_list.pop(0)) cur_ack = self.next_ack # print('len packet list=', len(self.packets_list)) if pack_sent < len(self.sliding_window): for pack in self.sliding_window[pack_sent:]: print('send pack ++', pack.seq_num) self.udp_socket.sendto( pack.get_udp_data(), (self.host_addr, self.emulator_port)) pack_sent += 1 self.seqnum_log.append(pack.seq_num) self.lock.release() start_time = time.time() print('TIMEOUT: self.next_ack', self.next_ack) # self.lock.acquire() for pack in self.sliding_window: self.udp_socket.sendto(pack.get_udp_data(), (self.host_addr, self.emulator_port)) self.seqnum_log.append(pack.seq_num) # print('timeout send: ', pack.seq_num) # self.lock.release() # Send all the content # print('SEND EOT', self.next_ack) self.udp_socket.sendto( packet.create_eot(self.next_ack).get_udp_data(), (self.host_addr, self.emulator_port))
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]) recvPort = int(commandlineArgs[3]) fileName = commandlineArgs[4] # open log file and to-be-saved file file = open(fileName, 'w+') arrivalLog = open('arrival.log', 'w+') # create packet receiving packet rSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) rSocket.bind(('', recvPort)) expectedSeqNum = 0 firstRun = True # print('Listenning on port: %d' % recvPort) count = 0 # start listening for packets while True: try: udpData = rSocket.recv(1024) except: print('Error: package error') sys.exit(2) # print('new packet') # process received packet dataPackage = packet.parse_udp_data(udpData) # the received packet is data if dataPackage.type == 1: # print('New packet: %d' % dataPackage.seq_num) # print('Expected: %d' % expectedSeqNum) # write newly received packet sequence number to log file arrivalLog.write('%d\n' % dataPackage.seq_num) # if the packet received has the expected sequence number # update expected sequence number and write data to file if dataPackage.seq_num == expectedSeqNum: file.write(dataPackage.data) expectedSeqNum += 1 expectedSeqNum = expectedSeqNum % packet.SEQ_NUM_MODULO ackPkg = packet.create_ack(dataPackage.seq_num) firstRun = False else: # packet sequence number is not expected # resend ack packet with last received sequence number lastAckSeqNum = expectedSeqNum - 1 if (lastAckSeqNum < 0): lastAckSeqNum = 31 ackPkg = packet.create_ack(lastAckSeqNum) # if it's first run and packet sequence number is not correct # don't send any ack packet if not firstRun: rSocket.sendto(ackPkg.get_udp_data(), (hostAddr, hostPort)) count += 1 elif dataPackage.type == 2: # packet type is eot, send a eot packet then exit rSocket.sendto( packet.create_eot(expectedSeqNum - 1).get_udp_data(), (hostAddr, hostPort)) sys.exit(0)
def main(): #get arguments emulator_hostname = sys.argv[1] emulator_port = sys.argv[2] receiver_port = sys.argv[3] output_file = sys.argv[4] #create udp connection to emulator udpSocket = socket(AF_INET, SOCK_DGRAM) udpSocket.bind(('', int(receiver_port))) #set up needed variables expected_sequence_number = 0 current_sequence_number = -1 first_packet = False #clean output file open("arrival.log", "w").close() open("output.txt", "w").close() #receive packet from emulator while True: udp_data, address = udpSocket.recvfrom(2048) packet_received = packet.parse_udp_data(udp_data) sequence_number = packet_received.seq_num #write into arrival.log # print("receiver receives: " + str(sequence_number)) if packet_received.type == 1: file_arrival = open("arrival.log", "a") file_arrival.write(str(sequence_number) + "\n") file_arrival.close() if sequence_number == expected_sequence_number: first_packet = True if packet_received.type == 1: packet_to_send = packet.create_ack(sequence_number) packet_to_send_encode = packet_to_send.get_udp_data() udpSocket.sendto(packet_to_send_encode, (emulator_hostname, int(emulator_port))) # print("receiver ack: " + str(packet_to_send.seq_num)) current_sequence_number = sequence_number expected_sequence_number = (1 + sequence_number) % 32 data = packet_received.data file_output = open(output_file, "a") file_output.write(data) file_output.close() elif packet_received.type == 2: # print("receive eot") packet_to_send = packet.create_eot(sequence_number) packet_to_send_encode = packet_to_send.get_udp_data() udpSocket.sendto(packet_to_send_encode, (emulator_hostname, int(emulator_port))) file_arrival = open("arrival.log", "a") file_arrival.write(str(packet_to_send.seq_num) + "\n") file_arrival.close() # print("receiver ack: " + str(packet_to_send.seq_num)) udpSocket.close() sys.exit() elif first_packet == False: continue else: packet_to_send = packet.create_ack(current_sequence_number) packet_to_send_encode = packet_to_send.get_udp_data() udpSocket.sendto(packet_to_send_encode, (emulator_hostname, int(emulator_port)))
def packets_sender(pkts, addr, port, rport): # Define useful constants base_seqnum = 0 base_i = 0 cur_pkt_i = 0 start_time = 0 end_time = 0 first = True pause = False # Call for global variables global N global last_ACKed_Seqnum global last_ACKed_Changed global rest_ACK # Create sender socket sender_Socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sender_Socket.bind(('', 0)) # Create new thread for ACK_receiver receiver = threading.Thread(target=ACK_receiver, args=(rport, )) receiver.daemon = True receiver.start() # Record the start time start_time = getTime() # Start sending packets while base_i < len(pkts): # Check if new ack is received, update timer and new base sequence number seqnum_lock.acquire() if last_ACKed_Changed: last_ACKed_Changed = False newBase = last_ACKed_Seqnum + 1 diff = newBase - base_seqnum if diff < 0: diff += 32 if newBase > 31: newBase -= 32 base_i += diff base_seqnum = newBase packet_timer = getTime() seqnum_lock.release() # Start timer for first time packet if first: packet_timer = getTime() first = False # See timer is expired or not t = getTime() if (t - packet_timer) > 100: cur_pkt_i = base_i packet_timer = getTime() pause = False # Send packets to the port if not pause: sender_Socket.sendto(pkts[cur_pkt_i].get_udp_data(), (addr, port)) # Record sent packet with open('seqnum.log', 'a+') as file: file.write("%d\n" % pkts[cur_pkt_i].seq_num) file.close() # Check if reached packet window limit or not cur_pkt_i += 1 if cur_pkt_i < (base_i + N) and cur_pkt_i < len(pkts): pause = False else: pause = True # Inform ACK_receiver thread to exit and send EOT rest_ACK_lock.acquire() rest_ACK = True rest_ACK_lock.release() EOT_pkt = packet.create_eot(len(pkts) - 1) sender_Socket.sendto(EOT_pkt.get_udp_data(), (addr, port)) receiver.join() # Record the end time end_time = getTime() # Calculate and record the transmission time transmission_time = end_time - start_time time_log = open('time.log', 'w+') time_log.write("%d\n" % transmission_time) time_log.close() return
def send_EOT(self, seq_num): """ Sends an EOT packet. """ socket(AF_INET, SOCK_DGRAM).sendto( packet.create_eot(seq_num).get_udp_data(), (self.hostname, self.ack_port))
serverSocket.bind(('', receiveDataPort)) expectingPacket = 0 f = open(filename, "w") while True: UDPdata, clientAddress = serverSocket.recvfrom( 2048 ) p = packet.parse_udp_data(UDPdata) returnPacket = None # if data if p.type == 1: if p.seq_num == expectingPacket % packet.SEQ_NUM_MODULO: f.write(p.data) # read and write to file expectingPacket = expectingPacket + 1 returnPacket = packet.create_ack( expectingPacket % packet.SEQ_NUM_MODULO - 1) # send if not expectingPacket == 0: # if received atleast one good packet serverSocket.sendto( returnPacket.get_udp_data() , (hostAddress, sendAckPort)) # if eot elif p.type == 2: returnPacket = packet.create_eot(-1) # send serverSocket.sendto( returnPacket.get_udp_data() , (hostAddress, sendAckPort)) break f.close() serverSocket.close()
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)) acknowledger.start() ## send packets print("start and end:", startpoint, endpoint) for p in range(startpoint, endpoint): print("sending: ", packets[p].seq_num) senderSocket.sendto(packets[p].get_udp_data(), (hostAddress, sendDataPort)) # wait on acknowledger acknowledger.join() senderSocket.sendto( packet.create_eot(-1).get_udp_data(), (hostAddress, sendDataPort)) senderSocket.close()
if message_packet.seq_num == expected_seq_num: done_first_packet = True cur_packet_seq_num = expected_seq_num if message_packet.type == 1: out_file_stream.write(message_packet.data) expected_seq_num = (expected_seq_num + 1) % packet.SEQ_NUM_MODULO elif not done_first_packet: continue else: cur_packet_seq_num = \ (packet.SEQ_NUM_MODULO + (expected_seq_num - 1)) % packet.SEQ_NUM_MODULO # send ack if message_packet.type == 2: # EOT ack_packet = packet.create_eot(cur_packet_seq_num) else: ack_packet = packet.create_ack(cur_packet_seq_num) out_socket.sendto(packet.get_udp_data(ack_packet), (emu_addr, emu_port)) if message_packet.type == 2: # since we got EOT, exit break out_file_stream.close()