def receive(sock, filename): # Open the file for writing try: file = open(filename, 'wb') except IOError: print('Unable to open: ', filename) return i = 0 expected_num = 0 arr_of_pack = [] while True: # Get's next packet pkt, addr = udt.recv(sock) if not pkt: break seq_num, data = packet.extract(pkt) print('Got packet :', seq_num) # Send back ACK dependent on if it is correct if seq_num == expected_num: print('Got expected Packet') print('Sending ACK :', expected_num) pkt = packet.make(expected_num) udt.send(pkt, sock, addr) file.write(data) expected_num += 1 if len(arr_of_pack) > expected_num: i = expected_num if arr_of_pack[expected_num] != 0: while i < len(arr_of_pack) and arr_of_pack[i] != 0: print('Writing cashed line to file.') file.write(arr_of_pack[i]) i = i + 1 expected_num = i else: pkt2, _ = udt.recv(sock) print('Staching duplicate or out of order Packet :', seq_num) if seq_num >= len(arr_of_pack): missing = seq_num + 1 - len(arr_of_pack) i = 0 while i <= missing: arr_of_pack.append(0) i = i + 1 arr_of_pack[seq_num] = data print('Sending ACK of duplicate or out of order Packet :', seq_num) pkt2 = packet.make(seq_num) udt.send(pkt2, sock, addr) print('File finished closeing') file.close()
def receive_gbn(sock): global base global timer global mutex # We have to make sure the connection is active, so the receiving logic # of the sender is within this try-catch block try: while True: # We wait to receive a packet ack, addr = udt.recv(sock) # To avoid race conditions with the sending mechanism, we use the mutex with mutex: # If the address of the sender is from the recipient or ours, # extract the data if addr == RECEIVER_ADDR or addr == SENDER_ADDR: seqnum, payload = packet.extract(ack) # If the packet is from us and the payload is FIN, # we signal the end of the receiving process to the main thread # and exit the listening loop if addr == SENDER_ADDR and payload == b'FIN': print("File sent successfully.\nClosing connection...") timer.stop() break # If we receive an ACK for a packet in the window, move the # base up to the packet following the ACK's sequence number if seqnum >= base and payload == b'ACK': base = seqnum + 1 timer.stop() except ConnectionError as e: print(e) # Here, we can assume we already sent the file and are waiting for the # client to close the connection. With a try-catch, we simply wait for the # exception to happen, stop the time to signal the sender, and print # that the connection was closed successfully try: while True: waste = udt.recv(sock) except ConnectionError as e: with mutex: timer.stop() print("Connection closed successfully.")
def receive_snw(sock): endStr = '' while endStr != 'END': pkt, senderaddr = udt.recv(sock) seq, data = packet.extract(pkt) endStr = data.decode() print("From: ", senderaddr, ", Seq# ", seq, endStr)
def receive(sock, filename): # Open the file for writing try: file = open(filename, 'wb') except IOError: print('Unable to open', filename) return expected_num = 0 #expected seq no of the packet received while True: # Get the next packet from the sender pkt, addr = udt.recv(sock) #these udt functions are defined in udt.py if not pkt: break seq_num, data = packet.extract(pkt) print('Got packet', seq_num) # Send back an ACK if seq_num == expected_num: print('Got expected packet') print('Sending ACK', expected_num) pkt = packet.make( expected_num, '') # ''implies an empty string because it's an ACK udt.send(pkt, sock, addr) expected_num += 1 file.write( data) #this copies the data into a.txt, initially it is empty else: print('Sending ACK', expected_num - 1) pkt = packet.make(expected_num - 1, '') udt.send(pkt, sock, addr) file.close()
def receive_gbn(sock): end = "" packetSeq = 0 sock.settimeout(10) try: receivedData = open("receivedData.txt", "a") while end != "END": try: pcket, senderAddress = udt.recv(sock) except socket.timeout(): print("Time out") break seq, packetData = packet.extract(pcket) print("Packet received: ", seq) print("Packet Data: ", packetData) if packetSeq != seq: print("Ack: ", packetSeq - 1) pcket = packet.make(packetSeq - 1) udt.send(pcket, sock, senderAddress) else: end = packetData.decode() pcket = packet.make(packetSeq) udt.send(pcket, sock, senderAddress) receivedData.write(end) packetSeq += 1 except IOError: print(IOError) return
def receive_snw(sock, pkt): endStr = '' global seq while endStr != 'END': pkt, senderaddr = udt.recv(sock) rSeq, data = packet.extract(pkt) #if received sequence from Receiver socket match sequence from this #Sender then alternate seq from 0 or 1 and break out while loop. if (rSeq == seq): if (seq == 0): seq = 1 else: seq = 0 break #Otherwise wrong sequence was received, resend correct sequence and data. else: print("Mismatched acks, resending") udt.send(pkt, sock, RECEIVER_ADDR) #Condition to check if timeout has been reach to end loop. if stop_event.is_set(): break
def receive(sock): global mutex global base global send_timer while True: pkt, _ = udt.recv(sock) ack_pack = packet.my_unpack(pkt) """ - Actualizar la base - Detener el timer - Recuerde utilizar mutex para las actualizaciones """ # print('Got ACK', ack_pack.ack) if (ack_pack.ack >= base): mutex.acquire() base = ack_pack.ack + 1 # print('Base updated', base) send_timer.stop() mutex.release() if not send_timer.running(): break mutex.acquire() if end_conn_timer: mutex.release() raise Exception('WAITING TIME EXCEDED')
def receive_snw(sock, pkt): global base global timer global mutex while base < len(pkt): # get out packet and server packet currentSequence, _ = packet.extract(pkt[base]) try: acknowledgement, _ = udt.recv(sock) except: print('*** ERROR: LOST CONNECTION TO SERVER') sys.exit(1) acknowledgement = int(acknowledgement.decode()) currentSequence = int(currentSequence) # see if we got the correct ack if acknowledgement == currentSequence: mutex.acquire() base += 1 timer.stop() mutex.release() else: print('\n*** ERROR: Received Incorrect Acknowledgement ***\n') print('Expected Acknowledgement: %i' % currentSequence) print('Received Acknowledgement: %i' % acknowledgement) sys.exit(0)
def receive(sock, filename): # Open the file for writing try: file = open(filename, 'wb') except IOError: print('Unable to open', filename) return expected_num = 0 while True: # Get the next packet from the sender pkt, addr = udt.recv(sock) if not pkt: break seq_num, data = packet.extract(pkt) print('Got packet', seq_num) # Send back an ACK if seq_num == expected_num: print('Got expected packet') print('Sending ACK', expected_num) pkt = packet.make(expected_num) udt.send(pkt, sock, addr) expected_num += 1 file.write(data) else: print('Sending ACK', expected_num - 1) pkt = packet.make(expected_num - 1) udt.send(pkt, sock, addr) file.close()
def receive_gbn(sock, sent): global received_packets global num_resent_packets global current_ack sock.settimeout(0.5) acknowledged = len(sent) count = 0 while count != acknowledged: try: for x in range(len(sent)): ACK, senderaddr = udt.recv(sock) ack, data = packet.extract(ACK) if ack not in received_packets and current_ack == ack: print("Confirm seq#: ", ack, "\n") received_packets.append(ack) sent.remove(ACK) current_ack += 1 count += 1 except socket.timeout: print("Resending") for x in sent: udt.send(x, sock, RECEIVER_ADDR) num_resent_packets += 1 return
def receive_gbn(sock, filename): # try to pen file for writing else throw error try: file = open(filename, 'wb') except IOError: print("Cannot open %s" % filename) return expected_seq = 0 while True: pkt, addr = udt.recv(sock) # receive packet and check if it's valid if not pkt: # if we receive a sentinel packet break receive break seq, data = packet.extract(pkt) # extract packet sequence number print("Received packet: %s" % seq) if seq == expected_seq: # if received sequence # is the expected sequence # send ACKs print("Received expected packet\nSending ACK: %s" % seq) pkt = packet.make(seq) udt.send(pkt, sock, addr) expected_seq += 1 # increment next expected sequence # and write data to file print("Writing data to file") file.write(data) else: # if not expected sequence # then send ACK for most recent ingested packet print("Sending ACK for latest packet: %s" % (expected_seq - 1)) pkt = packet.make(expected_seq - 1) udt.send(pkt, sock, addr) file.close()
def receive_snw(sock, pkt): #Mod rcvr by Jennifer global threads, sync threads += 1 #Put name in hat while not sync: #Spin Lock to Synchronize Execution continue while pkt_buffer: #While Packets still need to be sent mutex.acquire() #Lock print("2 - Acquired") #DEBUG timer.start() #Restart TTL p = pkt.pop() #Get next pkt #Checks for final ACK retry = RETRY_ATTEMPTS while retry: try: # Try ACK Check ack, recvaddr = udt.recv(sock) # If received, cleanup and pass baton timer.stop() mutex.release() time.sleep(SLEEP_INTERVAL) retry = RETRY_ATTEMPTS break except BlockingIOError: # Otherwise, check timer and restart if timer.timeout(): retry -= 1 udt.send(p, sock, RECEIVER_ADDR) timer.start() threads -= 1 #Remove name from hat
def receive(sock): global mutex expected_num = 0 while True: mutex.acquire() pkt, addr = udt.recv(sock) if not pkt: break seq_num, data = packet.extract(pkt) # packet 수신 print('Got packet', seq_num) if seq_num == expected_num: # 오류 없이 수신되는 경우 print('Expected packet. Sending ACK', expected_num) pkt = packet.make(expected_num) udt.send(pkt, sock, addr) rtt_q.append([pkt, sock, addr]) rtt_timer.append(time.time()) expected_num += 1 else: # 오류로 인해 순서가 잘못 수신되는 경우 print('Unexpected packet. Sending ACK', expected_num - 1) pkt = packet.make(expected_num - 1) udt.send(pkt, sock, addr) rtt_q.append([pkt, sock, addr]) rtt_timer.append(time.time()) time.sleep(UNIT_TIME) mutex.release()
def receive(sock, filename, drop_prob): try: file = open(filename, 'wb') except IOError: print('Unable to open', filename) return expected_num = 0 while True: pkt, addr = udt.recv(sock) if not pkt: break seq_num, data = packet.extract(pkt) print('Got packet', seq_num) if seq_num == expected_num: print('Sending ACK', expected_num) pkt = packet.make(expected_num) udt.send(pkt, sock, addr, drop_prob) expected_num += 1 file.write(data) else: print('Sending ACK', expected_num - 1) pkt = packet.make(expected_num - 1) udt.send(pkt, sock, addr, drop_prob) file.close()
def receive_snw(sock): endStr = '' expectedPacket = 0 # While FIN packet has not been received while endStr != 'END': pkt, senderaddr = udt.recv(sock) SEQ, data = packet.extract(pkt) endStr = data.decode() print("From: ", senderaddr, ", SEQ# ", SEQ) # The received packet was not expected. Send ACK with the correct SEQ number if expectedPacket != SEQ: print( 'This packet was not expected. Sending ACK %d' % expectedPacket, "\n") pkt = packet.make(expectedPacket) udt.send(pkt, sock, senderaddr) # This packet was expected. Send ACK with the next SEQ number expected else: print( 'Successfully received SEQ #%d. Sending ACK #%d' % (SEQ, expectedPacket), "\n") pkt = packet.make(expectedPacket) udt.send(pkt, sock, senderaddr) expectedPacket += 1 # Makes sure that the FIN packet is not added to the text if endStr != 'END': file.write(data.decode()) print('FIN has been ACK... Ending connection')
def receive_gbn(sock): # Fill here sock.settimeout(10) try: # open file file = open('./files/receiver_bio.txt', 'a') except: # cannot create file print('Could Access location') sys.exit(1) previous = -1 while True: try: clientPacket, clientAddress = udt.recv(sock) except: print('Server Shutting Down') sys.exit(1) clientSequence, clientData = packet.extract(clientPacket) print('Received client sequence', clientSequence) if previous + 1 == clientSequence: file.write(clientData.decode()) # write data to file previous = clientSequence # update last seen client sequence acknowledgement = packet.make(clientSequence, str(clientSequence).encode()) udt.send(acknowledgement, sock, clientAddress) return
def receive_snw(sock, pkt): global base global timer global mutex ackedpackets = 0 #use try in case of connection error try: #get the sequence number and payload from the packet passed in as a parameter #this contains the final sequence number and payload data in that packet fseqnum, fpayload = packet.extract(pkt) #ackedpacket is counting the total ACKS from Receiver.py #this loop runs until an ACK is received that is one number higher #than previously received because there is one final packet sent #when the payload packets are done while ackedpackets < fseqnum + 1: # unpack the ack packet received and increment ackpackets counter ack, addr = udt.recv(sock) ackedpackets += 1 with mutex: #unpack the seqnum and payload and update base so send_snw #knows to send the next packet in the sequence seqnum, payload = packet.extract(ack) base = seqnum + 1 #stop the timer because ACK was successfully reeived timer.stop() except ConnectionError as e: #mutex.release() print(e)
def receive_gbn(sock): initSeq = 0 seqList = [] #Holds Sequence numbers prev received f = open("receiver_bio.txt", "w") dataStr = '' while True: #while dataStr!='END': #print("In true loop") #DEBUG pkt, senderaddr = udt.recv(sock) seq, data = packet.extract(pkt) dataStr = data.decode() #Does not write if duplicate pkt or FIN pkt #print("data is "+data.decode()) #DEBUG print("receiver seq:%d, sender gave:%d" %(initSeq, seq)) #print("data:%s" %(dataStr)) if (seq == initSeq and not dataStr == "END"): #print("packet fine, writing to file") f.write(dataStr) ack = packet.make(initSeq, "ACK".encode()) initSeq = initSeq+1 udt.send(ack, sock, senderaddr) elif not seq == initSeq: #print("Not in ordered pkt received") ack = packet.make(initSeq, "ACK".encode()) elif dataStr == 'END': print("Received end, we're done") break f.close()
def receive_gbn(sock): seqList = [] #Holds Sequence numbers prev received f = open("gbn_receiver.txt", "w") dataStr = '' #While NO FIN pkt while dataStr != 'END': pkt, senderaddr = udt.recv(sock) seq, data = packet.extract(pkt) dataStr = data.decode() #Does not write if duplicate pkt or FIN pkt #print("data is "+data.decode()) #DEBUG if (seq not in seqList and not dataStr == "END"): f.write(dataStr) #Data recv, ensure duplicate packets are ignored seqList.append(seq) #print("From: ", senderaddr, ", Seq# ", seq, dataStr) #DEBUG #Send back ACK to confirm rcpt. #If ACK lost, retransmission happens on sender side :) ack = packet.make(seq, "ACK".encode()) udt.send(ack, sock, senderaddr) #TODO #I think instead of checking against an entire list we can #just have it check to see if ACK is #Sends ACK back to sender to confirm receipt #Obviously a list is unfeasible for modern comms #Ex.) Imagine trying to hold a list of ACKs for 512b from a 5GB file?? # That would be like 10 million numbers lol f.close()
def receive_gbn(sock): # Shared Resource Access global sync, base, sending, receiving # Spin lock to synchronize execution while not sync: continue retry = RETRY_ATTEMPTS + 1 base = 0 # Retry Loop while retry and (pkt_buffer or sending): with mutex: if timer.timeout() or not timer.running(): retry -= 1 timer.start() print("\n[I] RECV - Acquired Lock") for i in range(WINDOW_SIZE): try: # Try ACK Check ack, recvaddr = udt.recv(sock) seq, ack_data = packet.extract(ack) # Check for base packet reception if seq == base: print("[I] RECV - Got ACK Seq# {}".format(seq)) #sys.stderr.write("ACK on Seq# {}\n".format(seq)) #sys.stderr.flush() base += 1 pkt_buffer.pop(0) timer.stop() retry = RETRY_ATTEMPTS + 1 continue print( "[W] RECV - Got Wrong ACK Seq# {}, Expected {}".format( seq, base)) except BlockingIOError: continue time.sleep(SLEEP_INTERVAL) receiving = False print("[I] RECV - Terminating Thread") return
def mod_receive_snw(sock): endStr = '' f = open("bio2.txt", "w") while endStr != 'END': pkt, senderaddr = udt.recv(sock) seq, data = packet.extract(pkt) endStr = data.decode() print("From: ", senderaddr, ", Seq# ", seq, endStr) if (endStr != 'END'): f.write(endStr) f.close()
def receive_snw(sock): endStr = '' _seq = -1 while endStr != 'END': pkt, senderaddr = udt.recv(sock) seq, data = packet.extract(pkt) if _seq != seq: _seq = seq endStr = data.decode() print("From: ", senderaddr, ", Seq# ", seq, endStr) udt.send(b' ', sock, ('localhost', 9090))
def receive_sr(sock, windowsize): sock.settimeout(5) while True: try: pkt, senderAddr = udt.recv(sock) except: print('Shutting Down Server') sys.exit(1) seq, data = packet.extract(pkt) print(seq) ack = str(seq).encode() udt.send(ack, sock, senderAddr)
def receive_snw(sock): endStr = '' f = open("receiver_file_x.txt", "w") while endStr != 'END': pkt, senderaddr = udt.recv(sock) seq, data = packet.extract(pkt) endStr = data.decode() if endStr != "END": f.write(endStr) print("From: ", senderaddr, ", Seq# ", seq, "Data ", endStr, "\n") pkt = packet.make(seq, data) udt.send(pkt, sock, senderaddr)
def receive_snw(sock, pkt): sock.settimeout(0.5) acknowledged = False while not acknowledged: try: ACK, senderaddr = udt.recv(sock) ack, data = packet.extract(ACK) print("Confirm seq#: ", ack, "\n") acknowledged = True except socket.timeout: print("Resending") udt.send(pkt, sock, RECEIVER_ADDR) return
def receive_gbn(sock): # Fill here to handle acks global base, timer, mutex end = '' while end != 'END': pkt, senderaddr = udt.recv(sock) seq, data = packet.extract(pkt) end = data.decode() print("From: ", senderaddr, ", Seq# ", seq, end) if seq >= base: mutex.acquire() base = seq + 1 timer.stop() mutex.release()
def receive(sock): global mutex global base global send_timer while True: pkt, _ = udt.recv(sock) ack, _ = packet.extract(pkt) print('Got ACK', ack) if ack >= base: mutex.acquire() base = ack + 1 send_timer.stop() mutex.release()
def receive_snw(sock, pkt): # Shared Resource Access global sync, alive # Spin lock to synchronize execution while not sync: continue # While Packets still exist while pkt_buffer: # Manually lock mutex.acquire() # Debugging info print("[I] RECV - Acquired Lock") # Retry Delay timer.start() # Get Packet p = pkt.pop() # R retry = RETRY_ATTEMPTS while retry: try: # Try ACK Check ack, recvaddr = udt.recv(sock) # If received, cleanup and pass baton timer.stop() mutex.release() time.sleep(SLEEP_INTERVAL) retry = RETRY_ATTEMPTS break except BlockingIOError: # Otherwise, check timer and restart if timer.timeout(): retry -= 1 udt.send(p, sock, RECEIVER_ADDR) timer.start() # Remove name from hat alive = False
def receive_gbn(sock, sent): sock.settimeout(0.5 * 50) acknowledged = len(sent) count = 0 while count != acknowledged: try: for x in range(len(sent)): ACK, senderaddr = udt.recv(sock) ack, data = packet.extract(ACK) print("Confirm seq#: ", ack, "\n") acknowledged += 1 except socket.timeout: print("Resending") for x in sent: udt.send(x, sock, RECEIVER_ADDR) return
def receive_snw(sock): endStr = '' _seq = -1 while True: pkt, senderaddr = udt.recv(sock) seq, data = packet.extract(pkt) if _seq != seq: _seq = seq endStr = data.decode() sys.stderr.write("From: {}, Seq# {}\n".format(senderaddr, seq)) sys.stderr.flush() if endStr == 'END': return sys.stdout.write(endStr) sys.stdout.flush() udt.send(b' ', sock, ('localhost', 9090))
def receive(sock): global mutex global base global send_timer while True: pkt, _ = udt.recv(sock); ack, _ = packet.extract(pkt); # If we get an ACK for the first in-flight packet print('Got ACK', ack) if (ack >= base): mutex.acquire() base = ack + 1 print('Base updated', base) send_timer.stop() mutex.release()