Demo entry 5958792

Sender

   

Submitted by anonymous on Sep 09, 2016 at 01:32
Language: Python 3. Code size: 4.6 kB.

"""Sender program which creates data packets and sends them to receiver via 
transmission medium channel, and waits on response packets from receiver.
Written by Hazel Erickson and Kaitlin Haines, 2016"""

import sys
import socket
import select
import os.path
from struct import *

class packet(object):
    
    def __init__(self, packet_type, seqno, dataLen, data):
        self.magicno = 0x497E
        # data Packet = 1, acknowledgement Packet = 0
        self.packet_type = packet_type 
        self.seqno = seqno # integer value
        self.dataLen = dataLen # integer value between 0 and 512
        self.data = data # field containing the actual user data
        
    def pack(self):
        b = pack("!I3i" + str(self.dataLen) + "s", self.magicno, 
                 self.packet_type, self.seqno, self.dataLen, self.data)
        return b

# command line $python myfile.py var1 var2 var3 filename

# port numbers for the two sender sockets
port_1 = int(sys.argv[1])
port_2 = int(sys.argv[2])

# port number for the channel socket
port_3 = int(sys.argv[3])

# file name
filename = sys.argv[4]

host = '127.0.0.1'    # Loopback address    

seqno_next = 0
exit_flag = False
exit_flag2 = False
packets_sent = 0
read_amount = 0

# Create socket s_out and s_in to sendand receive packets
if ((port_1, port_2 > 1024) and (port_1, port_2 < 64000)):
    print("Creating sockets")
    try:
        s_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    except socket.error:
        print('Failed to create socket s_in') 
        
    try:
        s_out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    except socket.error:
        print('Failed to create socket s_out')
    
    # Bind s_in and s_out
    print("Binding sockets")
    s_in.bind((host, port_1))
    s_out.bind((host, port_2))     
    
    # Connect s_out to the host and port
    print("Connecting s out to cs in")
    s_out.connect((host, port_3))
    
    # s_out.sendto(package.encode()) not required 
    # Check filename exists
    if not os.path.exists(filename):
        sys.exit()  
        
    while exit_flag == False:
        # Attepts to read up to 512 bytes from the open file
        with open(filename, mode='rb+') as file:
            print("Reading data from file")
            file.seek(read_amount)
            data = file.read(512)
            read_amount += 512
            
        # Checks size of data and create data packet
        if len(data) == 0:
            print("Creating empty packet")
            size = 0
            data_packet = packet(1, seqno_next, 0, b'')
            packed_data = data_packet.pack()     
            exit_flag = True
            packets_sent += 1
        else:
            print("Creating data packet")
            data_packet = packet(1, seqno_next, len(data), bytes(data))
            packed_data = data_packet.pack()
            packets_sent += 1
            

        exit_flag2 = False
       
        while exit_flag2 == False: 
            print("Sending packet to channel")
            try:
                s_out.sendto(packed_data, (host, port_3))
                packets_sent = packets_sent + 1
            except ConnectionRefusedError:
                print("Connection lost")
            
            readable, _, _ = select.select([s_in], [], [], 1)
            
            print("Checking if s_in is readable")
    
            if readable:
                data_packet2, addr = s_in.recvfrom(1024)
                
                magicno, packet_type, seqno, length = unpack_from("!I3i", data_packet2[:16])
                unpacked_data = unpack_from("%ds" % length, data_packet2[16:])   
                
                if (int(magicno) == 18814):
                    if (length == 0):
                        if (packet_type == 0):
                            if exit_flag == True:
                                print("Packets sent: " + str(packets_sent))
                                s_in.close()
                                s_out.close()
                                sys.exit()                            
                            if seqno == seqno_next:      
                                exit_flag2 = True
                                
                        seqno_next = 1 - seqno_next
                        
            else: print("TIMEOUT")
            
    
else:
    print("Incorrect port size")
                
            
        

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).