Esempio n. 1
0
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
Esempio n. 2
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(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()
Esempio n. 4
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)
Esempio n. 5
0
    def run(self):
        """
        This method defines the task of this thread. Called by thread.start()
        """
        global seq_num
        global timer
        global pkt_buffer

        '''Sending packets until all the packets are ACKed'''
        while True:

            '''Before sending, check whether there is unsent packet in the buffer'''
            if send_condition():

                '''Send the next packet'''
                udt.send(self.sock, self.rcv_addr, pkt_buffer[seq_num])

                '''|----------------------------------------------|'''
                '''| When base equals to seq_num, start the timer |'''
                '''|                                              |'''
                '''|                 Fill in here                 |'''
                '''|                                              |'''
                '''|-------------------- End ---------------------|'''

                '''Increment the sequence number by one'''
                seq_num += 1

                '''Check whether all packets are ACKed'''
            elif end_condition():
                break
Esempio n. 6
0
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
Esempio n. 7
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()
Esempio n. 8
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()
Esempio n. 9
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() 
Esempio n. 10
0
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
Esempio n. 11
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()
Esempio n. 12
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
Esempio n. 13
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()
Esempio n. 14
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
Esempio n. 15
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)
Esempio n. 16
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')
Esempio n. 17
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
Esempio n. 18
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
Esempio n. 19
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
Esempio n. 20
0
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()
Esempio n. 21
0
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()
Esempio n. 22
0
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))
Esempio n. 23
0
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)
Esempio n. 24
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()
Esempio n. 25
0
def rtt_queue():
    global mutex
    global rtt_q
    global rtt_timer

    while (True):
        mutex.acquire(0)
        if len(rtt_q) > 0 and time.time() - rtt_timer[0] >= RTT / 2:
            rtt_timer.pop(0)
            pac, soc, addr = rtt_q.pop()
            udt.send(pac, soc, addr)
        mutex.release()
Esempio n. 26
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)
Esempio n. 27
0
def send_gbn(sock, packets):
    global mutex
    global base
    global timer

    # get packets from file and set all necessary values
    num_packets = len(packets)
    print("Packets to be sent: %s" % num_packets)
    window_size = get_window_size(num_packets)
    window_start = 0
    next_to_send = 0
    base = 0

    # Start the receiver thread
    print("Starting gbn receive thread")
    _thread.start_new_thread(receive_gbn, (sock,))

    while base < num_packets:
        # set mutex lock to this thread to execute send tasks
        # send all packets in given window
        mutex.acquire()
        while next_to_send < window_start + window_size:
            print("Sending sequence #: %s" % next_to_send)
            udt.send(packets[next_to_send], sock, RECEIVER_ADDR)
            next_to_send += 1

        # Start the timer
        if not timer.running():
            print("Starting window timer")
            timer.start()

        # Wait until a timer times out and pass mutex lock to receive thread
        while timer.running() and not timer.timeout():
            mutex.release()
            print("Waiting for ACKs")
            time.sleep(SLEEP_INTERVAL)
            mutex.acquire()
        # if we time out or we have not received ACKs for all window packets
        # then we reset window. Else we move the window
        if timer.timeout() or ((window_start + window_size) > base):
            print("Window timed out")
            timer.stop()
            next_to_send = window_start
        else:
            next_to_send = base
            window_start = base
            print("Moving window")
            window_size = get_window_size(num_packets)
        mutex.release()

    # Send sentinel packets
    udt.send(packet.make_empty(), sock, RECEIVER_ADDR)
    print("All packets have been sent")
Esempio n. 28
0
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)
Esempio n. 29
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
Esempio n. 30
0
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
Esempio n. 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()