Пример #1
0
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
Пример #2
0
    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
Пример #3
0
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()
Пример #4
0
    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))
Пример #5
0
    def send_ack(self, seq_num: int):
        """ Sends an ACK packet for a sequence number.

        Args:
            seq_num: Sequence number of the packet to mention in the ACK.
        """
        socket(AF_INET, SOCK_DGRAM).sendto(
            packet.create_ack(seq_num).get_udp_data(),
            (self.hostname, self.ack_port))
Пример #6
0
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()
Пример #7
0
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()
Пример #8
0
            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()
Пример #9
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)))
Пример #10
0
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)