Exemple #1
0
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):
    # 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()
Exemple #3
0
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()
Exemple #4
0
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
Exemple #5
0
def send_snw(sock):
    # Access to shared resources
    global switch
    # Track packet count
    seq = 0

    # Open file as read
    with open(filename, "r") as f:
        # iterate through file at increments of packet size
        for p in iter(partial(f.read, PACKET_SIZE), b''):
            # Lock packet transfer
            with mutex:

                # Generate Packet & Link Buffer
                data = p.encode()
                pkt = packet.make(seq, data)
                pkt_buffer.append(pkt)

                # Handle Thread Timing
                switch = True

                # Send Packet and Increment Sequence
                print("Sending seq# ", seq, "\n")
                udt.send(pkt, sock, RECEIVER_ADDR)
                seq += 1

            # Delay Mutex for sister thread
            time.sleep(SLEEP_INTERVAL)
            if not p:
                break
        # Prepare & Send END packet
        with mutex:
            pkt = packet.make(seq, "END".encode())
            pkt_buffer.append(pkt)
            udt.send(pkt, sock, RECEIVER_ADDR)
Exemple #6
0
def send_snw(sock, filename):
    # open file to be read.
    file = open(filename, "r", encoding="utf-8")
    #The end of file, nothing else to read.
    while (file.tell() != 3460):
        ack = seq
        #Read bytes from file as determines by PACKET_SIZE
        data = file.read(PACKET_SIZE)

        data = data.encode()
        pkt = packet.make(seq, data)
        print("Sending seq# ", seq, "\n")

        #Loop through sending attempts until sequence as been updated
        #signaling packet has been properly sent and ack received.
        while (ack == seq):

            udt.send(pkt, sock, RECEIVER_ADDR)
            #Start thread for receiver_snw.
            snwThread = Thread(target=receive_snw, args=(sock, pkt))
            snwThread.start()
            #Timeout for receiver_snw thread to complete then continue down path.
            snwThread.join(timeout=.5)
            #Set stop event so receive_snw stops after timeout.
            stop_event.set()

    #Sends end of file flag to Receiver socket signaling file has been fully read.
    pkt = packet.make(seq, "END".encode())
    udt.send(pkt, sock, RECEIVER_ADDR)
Exemple #7
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()
Exemple #8
0
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() 
Exemple #9
0
def send_gbn(sock):
    global num_sent_packets
    global num_resent_packets
    seq = 0
    packets = []
    start_time = time.time()
    f = open(input("File Name: "), 'rb')
    data = f.read(PACKET_SIZE)
    while data:
        pkt = packet.make(seq, data)
        packets.append(pkt)
        data = f.read(PACKET_SIZE)
        seq += 1
    pkt = packet.make(seq, "END".encode())
    packets.append(pkt)

    while packets:
        packetsSent = []
        for x in range(WINDOW_SIZE):
            pkt = packets.pop(0)
            packetsSent.append(pkt)
            udt.send(pkt, sock, RECEIVER_ADDR)
            num_sent_packets += 1
            time.sleep(TIMEOUT_INTERVAL)
        receive_gbn(sock, packetsSent)
    end_time = time.time()
    print("Total number of packets sent:", num_sent_packets, "\n")
    print("Number of packets resent:", num_resent_packets, "\n")
    print("Time taken to complete file transfer:", end_time - start_time,
          "seconds")
    return
Exemple #10
0
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')
Exemple #11
0
def send_snw(sock): #mod sndr by Jennifer
    global threads, sync
    threads += 1 #Put name in hat
    seq = 0 #Tracks pkt count

    # Open local stream
    with open(filename, "r") as f:
        data = True #Do While Trick
        while data: 
            with mutex: #Lock Context
                print("1 - Acquired w/ {}".format(seq+1)) #DEBUG

                # Generate Packet & Link Buffer
                data = f.read(PACKET_SIZE).encode()
                pkt = packet.make(seq, data)
                pkt_buffer.append(pkt)

                sync = True #Handles Thread timing

                # Send Packet and Increment Sequence
                udt.send(pkt, sock, RECEIVER_ADDR)
                seq += 1

            # Delay Mutex for sister thread
            time.sleep(SLEEP_INTERVAL) 

        # Prepare & Send END packet
        with mutex:
            pkt = packet.make(seq, "END".encode())         
            pkt_buffer.append(pkt)
            udt.send(pkt, sock, RECEIVER_ADDR)                

    threads -= 1 #Remove name from hat
Exemple #12
0
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()
Exemple #13
0
def send_gbn(sock):
    # Access to shared resources
    global sync, data, sending, receiving

    # Track packet count
    seq = 0

    # Set data proper
    data = []

    # Open local stream
    with open(filename, "r") as f:

        print("[I] SEND - Initial Stream")

        for i in range(WINDOW_SIZE):
            data = f.read(PACKET_SIZE).encode()
            if data:
                print("[I] SEND - Pushing to Buffer Pkt# {}".format(seq))
                pkt = packet.make(seq, data)
                pkt_buffer.append((pkt, seq))
                seq += 1

        _base = 0

        # Sequential File Access
        while receiving and (data or pkt_buffer):

            # Delay Mutex for sister thread
            time.sleep(SLEEP_INTERVAL)

            with mutex:

                sync = True

                print("\n[I] SEND - Acquired Lock")
                for pkt in pkt_buffer:
                    print("[I] SEND - Sending Pkt# {}".format(pkt[1]))
                    udt.send(pkt[0], sock, RECEIVER_ADDR)

            for i in range(base - _base):
                data = f.read(PACKET_SIZE).encode()
                if data:
                    pkt = packet.make(seq, data)
                    pkt_buffer.append((pkt, seq))
                    seq += 1
            _base = base

    # Prepare & Send END packet
    with mutex:
        for i in range(0, 3):
            pkt = packet.make(seq, "END".encode())  # Prepare last packet
            pkt_buffer.append(pkt)
            udt.send(pkt, sock, RECEIVER_ADDR)  # Send EOF

    print("[I] SEND - Terminating Thread, Buffer Size: {}".format(
        len(pkt_buffer)))
    sending = False
    return
def send_gbn(sock):
    global base, timer, mutex
    pck_store = []
    pkt_seq = 0

    filePath = 'Bio.txt'  #this can be any desired file path or file name
    file = open(filePath,'rb')
    data = " "

    '''making the packets and storing them in a list'''
    while data:
        data = file.read(PACKET_SIZE)
        pck_store.append(packet.make(pkt_seq, data))
        pkt_seq= pkt_seq + 1

    #reseting packet sequence number
    pkt_seq = 0
    '''setting up a variable to store the values within the base of
    the window and its top'''
    window = WINDOW_SIZE
    base = 0

    '''starting thread'''
    _thread.start_new_thread(receive_gbn,(sock,))
    print("Starting....")
    while base < len(pck_store):
        mutex.acquire()
        '''Starting timer.......'''''
        if not timer.running():
            timer.start()

        '''Sending the packets in window and checking that the current pkt sequence 
        is less than the packets stored in buffer'''
        while pkt_seq < (base + window) and pkt_seq < len(pck_store):
            udt.send(pck_store[pkt_seq], sock, RECEIVER_ADDR)
            print("Sending seq#", pkt_seq, "\n")
            pkt_seq = pkt_seq + 1

        '''checking for a timer timeout, updating window if no timeout has occurred'''
        if timer.timeout():
            timer.stop()
            print("Timeout occurred, resetting.......")
            pkt_seq = base
        else:
            '''updating window'''''
            window = min((len(pck_store)-base),WINDOW_SIZE)

        while timer.running() and not timer.timeout():
            mutex.release()
            time.sleep(SLEEP_INTERVAL)
            print("Sleeping......")
            mutex.acquire()
        mutex.release()

    '''sending last packet with the content END'''
    pkt = packet.make(pkt_seq, "END".encode())
    udt.send(pkt, sock, RECEIVER_ADDR)
    file.close()
def send_snw(sock):
	# Fill out the code here
    seq = 0
    while(seq < 20):
        data = generate_payload(40).encode()
        pkt = packet.make(seq, data)
        print("Sending seq#", seq, "\n")
        udt.send(pkt, sock, RECEIVER_ADDR)
        seq = seq+1
        time.sleep(TIMEOUT_INTERVAL)
    pkt = packet.make(seq, "END".encode())
    udt.send(pkt, sock, RECEIVER_ADDR)
Exemple #16
0
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()
Exemple #17
0
def send_gbn(sock):
    global base, timer, mutex
    packetStore = []
    packetSeq = 0
    try:
        file = open("bio.txt", "r")  # reads bio.txt file
        data = ' '
        while data:
            data = file.read(PACKET_SIZE)  # makes the packets
            packetStore.append(packet.make(
                packetStore, data))  # stores packets in packet list
            packetSeq += 1  # updates packet sequence counter

        base = 0
        window = WINDOW_SIZE
        packetSeq = 0

        # Starting a new thread
        _thread.start_new_thread(receive_gbn(sock))

        while base < len(packetStore):
            mutex.acquire()

            if not timer.running():
                timer.start()

            while packetSeq < len(packetStore) & packetSeq < base + window:
                print("\nSending Packet Sequence #:", packetSeq)
                udt.send(packetStore[packetSeq], sock, RECEIVER_ADDR)

            while not timer.timeout() and timer.running():
                print("Sleeping")
                mutex.release()
                time.sleep(SLEEP_INTERVAL)
                mutex.acquire()

            mutex.release()

            if not timer.timeout():
                window = min((len(packetStore) - base), WINDOW_SIZE)
            else:
                print("\nTimeout occurred")
                timer.stop()
                packetSeq = base

        lastPacket = packet.make(packetSeq, "End".encode())
        udt.send(lastPacket, sock, RECEIVER_ADDR)
        file.close()

    except IOError:
        print(IOError)
        return
Exemple #18
0
def send_snw(sock):
    seq = 0
    f = open(input("FileName: "), 'rb')
    while True:
        data = f.read(PACKET_SIZE)
        if not data:
            break
        pkt = packet.make(seq, data)
        print("Sending seq# ", seq, "\n")
        udt.send(pkt, sock, RECEIVER_ADDR)
        seq = seq + 1
        time.sleep(TIMEOUT_INTERVAL)
        receive_snw(sock, pkt)
    pkt = packet.make(seq, "END".encode())
    udt.send(pkt, sock, RECEIVER_ADDR)
Exemple #19
0
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()
Exemple #20
0
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
Exemple #21
0
def receive_snw(sock, filename):
    global ack
    endStr = ''
    prevData = ''  #Holds previous data incase of packet drop from Receiver to Sender
    #If data from packet contains 'END', receive stream has ended.
    while endStr != 'END':
        #Extracts packet and sender address from socket.
        pkt, senderaddr = udt.recv(sock)
        #Extracts sequence number and data from packet.
        seq, data = packet.extract(pkt)
        #If data equals the previous data sent then packet was dropped from Receiver
        #to sender. Resend previous ack number with data.
        if data == prevData:
            print(
                "Data received is previous data received. Resending previous ack."
            )
            if (ack == 0):
                pkt = packet.make(ack + 1, data)
                udt.send(pkt, sock, senderaddr)
            else:
                pkt = packet.make(ack - 1, data)
                udt.send(pkt, sock, senderaddr)

        #If sequence does not equal ack from Sender then packet dropped causing
        #misorder. Send the correct sequence from Receiver back to Sender.
        elif (seq != ack):
            print("Seq ", seq, " and ack ", ack,
                  " do not match. Waiting for resend.")
            pkt = packet.make(ack, data)
            udt.send(pkt, sock, senderaddr)

        #Sequence matches ack from Sender.
        #Write data to new file, incrememnt Receiver ack, send back the Sender ack
        #to acknowledge receieved proper sequenced number.
        else:
            print("Seq ", seq, " and ack ", ack, " match. Will write to file.")
            endStr = data.decode()
            file = open(filename, "a")
            file.write(endStr)
            pkt = packet.make(ack, data)
            prevData = data

            if (ack == 0):
                ack = 1
            else:
                ack = 0
            udt.send(pkt, sock, senderaddr)
Exemple #22
0
def package_payload(payload):
    # We split up the payload into packets with packet size, while keeping track of the
    # sequence number and the data to turn into a packet
    packets = []
    packet_data = b''
    seq_num = 0

    for i in range(len(payload)):
        packet_data = packet_data + payload[i:i+1]
        if len(packet_data) == PACKET_SIZE:
            packets.append(packet.make(seq_num, packet_data))
            packet_data = b''
            seq_num += 1
    if len(packet_data) > 0:
        packets.append(packet.make(seq_num, packet_data))
    
    return packets
Exemple #23
0
def mod_snw(sock):
	seq = 0

	#Opens file and reads first 512 bytes to get the ball rolling
	#From there, sends those 512 and reads another 512 bytes
	#Once file is emptied, sends FIN Packet
	with open("helloFr1end.txt", "rb") as file:
		data = file.read(PACKET_SIZE)
		while data:
			pkt = packet.make(seq, data)
			print("Sending seq ", seq, "\n")
			udt.send(pkt, sock, RECEIVER_ADDR)
			seq = seq+1
			time.sleep(TIMEOUT_INTERVAL)
			data = file.read(PACKET_SIZE)
		
		pkt = packet.make(seq, "END".encode())
		udt.send(pkt, sock, RECEIVER_ADDR)
def send(sock, filename, drop_prob):
    global mutex
    global base
    global send_timer

    try:
        file = open(filename, 'rb')
    except IOError:
        print('Unable to open', filename)
        return

    packets = []
    seq_num = 0
    while True:
        data = file.read(PACKET_SIZE)
        if not data:
            break
        packets.append(packet.make(seq_num, data))
        seq_num += 1

    num_packets = len(packets)
    print('Total number of packets: ', num_packets)
    window_size = set_window_size(num_packets)
    next_to_send = 0
    base = 0

    _thread.start_new_thread(receive, (sock, ))

    while base < num_packets:
        mutex.acquire()
        while next_to_send < base + window_size:
            print('Sending packet', next_to_send)
            udt.send(packets[next_to_send], sock, RECEIVER_ADDR, drop_prob)
            next_to_send += 1

        if not send_timer.running():
            print('Starting timer')
            send_timer.start()

        while send_timer.running() and not send_timer.timeout():
            mutex.release()
            print('Sleeping')
            time.sleep(SLEEP_INTERVAL)
            mutex.acquire()

        if send_timer.timeout():
            print('Timeout')
            send_timer.stop()
            next_to_send = base
        else:
            print('Shifting window')
            window_size = set_window_size(num_packets)
        mutex.release()

    udt.send(packet.make_empty(), sock, RECEIVER_ADDR, drop_prob)
    file.close()
def send(sock, numbers):
    #global mutex
    global base
    global send_timer

    # Add all the packets to the buffer
    packets = []
    seq_num = 0
    while True:
        if seq_num >= len(numbers):
            break
        data = numbers[seq_num]
        packets.append(packet.make(seq_num, data))
        seq_num += 1

    num_packets = len(packets)
    print('I got', num_packets, ' to send')
    window_size = set_window_size(num_packets)
    next_to_send = 0
    base = 0

    # Start the receiver thread
    thread.start_new_thread(receive, (sock, ))

    while base < num_packets:
        mutex.acquire()
        # Send all the packets in the window
        while next_to_send < base + window_size:
            print('Sending packet', next_to_send)
            sock.sendto(packets[next_to_send], RECEIVER_ADDR)
            next_to_send += 1

        # Start the timer
        if not send_timer.running():
            print('Starting timer')
            send_timer.start()

        # Wait until a timer goes off or we get an ACK
        while send_timer.running() and not send_timer.timeout():
            mutex.release()
            print('Sleeping')
            time.sleep(SLEEP_INTERVAL)
            mutex.acquire()

        if send_timer.timeout():
            # Looks like we timed out
            print('Timeout')
            send_timer.stop()
            next_to_send = base
        else:
            print('Shifting window')
            window_size = set_window_size(num_packets)
        mutex.release()

    # Send empty packet as sentinel
    sock.sendto(packet.make_empty(), RECEIVER_ADDR)
Exemple #26
0
def send_snw(sock):

    # Access to shared resources
    global sync, data, alive

    # Track packet count
    seq = 0

    # Open local stream
    with open(filename, "r") as f:

        # Sequential File Access
        while data:

            # Lock Context
            with mutex:

                # Debugging Info
                print("[I] SEND - Acquired Lock")

                # Generate Packet & Link Buffer
                data = f.read(PACKET_SIZE).encode()
                pkt = packet.make(seq, data)
                pkt_buffer.append(pkt)

                # Handle Thread Timing
                sync = True

                # Send Packet and Increment Sequence
                udt.send(pkt, sock, RECEIVER_ADDR)
                seq += 1

            # Delay Mutex for sister thread
            time.sleep(SLEEP_INTERVAL)

        # Prepare & Send END packet
        with mutex:
            pkt = packet.make(seq, "END".encode())  # Prepare last packet
            pkt_buffer.append(pkt)
            udt.send(pkt, sock, RECEIVER_ADDR)  # Send EOF
            alive = false
def send_gbn(sock):
    seq = 0
    packets = []
    f = open(input("File Name: "), 'rb')
    data = f.read(PACKET_SIZE)
    while data:
        pkt = packet.make(seq, data)
        packets.append(pkt)
        data = f.read(PACKET_SIZE)
        seq += 1
    pkt = packet.make(seq, "END".encode())
    packets.append(pkt)

    while packets:
        packetsSent = []
        for x in range(WINDOW_SIZE):
            pkt = packets.pop(0)
            packetsSent.append(pkt)
            udt.send(pkt, sock, RECEIVER_ADDR)
            time.sleep(TIMEOUT_INTERVAL)
            receive_gbn(sock, packetsSent)
Exemple #28
0
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)
Exemple #29
0
def receive_gbn(sock):
    previous = -1
    packets = []
    addr_connection = None
    
    while True:
        try:
            p, addr = udt.recv(sock)
            seq_num, payload = packet.extract(p)

            # If this is a new connection, save address and store expected payload length
            if addr_connection == None and seq_num == 0:
                addr_connection = addr

            # if packet received was from the expected sender...
            if addr == addr_connection:

                # if packet signals end of transmission, stop listening for packets
                if seq_num == -1 and payload == b'FIN':
                    print("File received successfully.")
                    break
                
                # if sequence number is what we're expecting, send an ack and append packet contents to packet stack
                if seq_num == previous + 1:
                    udt.send(packet.make(seq_num, b'ACK'), sock, addr)
                    packets.append((seq_num, payload))
                    previous += 1
                    print("Received packet: {}".format(seq_num))
                
                # retransmit ack for last-received packet
                else:
                    if len(packets) > 0:
                        udt.send(packet.make(packets[-1][0], b'ACK'), sock, addr) 
        
        except ConnectionError as e:
            print(e)
            return -1

    # because packet list contains sequence numbers, simply form a list 
    return list(dict(packets).values())
def receive_gbn(sock):
    '''file created to save received packets'''
    try:
        file_out = open('receiver_bio.txt', 'a')
    except IOError:
        print("File not created")
        return

    endStr = ''
    expected_seq = 0
    '''if socket doesnt receive info in 10 seconds, then end communication'''
    sock.settimeout(10)
    while endStr != 'END':
        '''checking if sender continues to transmit data'''
        try:
            pkt, senderaddr = udt.recv(sock)
        except socket.timeout:
            print('Sender seems inactive......')
            print('Shutting down receiver.....')
            break
        seq, data = packet.extract(pkt)
        print("Received Packet: ",seq)
        if seq == expected_seq:
            '''extracting valid packet contents and appending contents to receiver_bio.txt file'''
            endStr = data.decode()
            print("From: ", senderaddr, ", Seq# ", seq, endStr)
            print("Sending ACK:", expected_seq)
            pkt = packet.make(expected_seq)
            udt.send(pkt, sock, senderaddr)
            file_out.write(endStr)
            expected_seq = expected_seq + 1
        else:
            ##Sending last valid ACK
            print("Sending ACK:",expected_seq-1)
            pkt = packet.make(expected_seq-1)
            udt.send(pkt,sock,senderaddr)

    print("End of transmission")
    file_out.close()
Exemple #31
0
def send(sock, filename):
    global mutex
    global base
    global send_timer

    # Open the file
    try:
        file = open(filename, 'rb')
    except IOError:
        print('Unable to open', filename)
        return
    
    # Add all the packets to the buffer
    packets = []
    seq_num = 0
    while True:
        data = file.read(PACKET_SIZE)
        if not data:
            break
        packets.append(packet.make(seq_num, data))
        seq_num += 1

    num_packets = len(packets)
    print('I gots', num_packets)
    window_size = set_window_size(num_packets)
    next_to_send = 0
    base = 0

    # Start the receiver thread
    _thread.start_new_thread(receive, (sock,))

    while base < num_packets:
        mutex.acquire()
        # Send all the packets in the window
        while next_to_send < base + window_size:
            print('Sending packet', next_to_send)
            udt.send(packets[next_to_send], sock, RECEIVER_ADDR)
            next_to_send += 1

        # Start the timer
        if not send_timer.running():
            print('Starting timer')
            send_timer.start()

        # Wait until a timer goes off or we get an ACK
        while send_timer.running() and not send_timer.timeout():
            mutex.release()
            print('Sleeping')
            time.sleep(SLEEP_INTERVAL)
            mutex.acquire()

        if send_timer.timeout():
            # Looks like we timed out
            print('Timeout')
            send_timer.stop();
            next_to_send = base
        else:
            print('Shifting window')
            window_size = set_window_size(num_packets)
        mutex.release()

    # Send empty packet as sentinel
    udt.send(packet.make_empty(), sock, RECEIVER_ADDR)
    file.close()