receiver.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from packet import packet
  2. import socket, sys
  3. # save values needed to talk to host emulator
  4. haddr = sys.argv[1] # network host address
  5. dport = int(sys.argv[2]) # dest port on host
  6. rport = int(sys.argv[3]) # recv port for this app
  7. received = sys.argv[4] # filename to be used to record recvd data
  8. # try opening the file
  9. try:
  10. msgfile = open(received, 'a')
  11. except IOError:
  12. sys.stderr.write("Failed to open file to write data. Stop being terrible at life pls")
  13. raise SystemExit
  14. # logfile (received packets)
  15. # at end call things.close()
  16. arrlog = open("arrival.log", "a")
  17. # some vars needed for execution
  18. expected = 0 # next packet # expected
  19. confirmed = None # last confirmed packet
  20. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # socket!
  21. sock.bind(('', rport)) # set socket to recv on rport
  22. pack_size = 512 # packet size in bytes
  23. # let's get this bread! I mean packets. yes, I re-used that joke.
  24. while(True):
  25. pack, addr = sock.recvfrom(pack_size)
  26. # if we can't get a packet
  27. if (not pack):
  28. break
  29. else:
  30. packet = packet.parse_udp_data(pack)
  31. snum = packet.seq_num
  32. arrlog.write(str(snum) + "\n")
  33. if (snum == expected): # got the next packet
  34. if (packet.type == 2): # EOT packet
  35. # send EOT and exit
  36. sock.sendto(packet.create_eot(snum).get_udp_data(), (haddr, dport))
  37. break
  38. elif (packet.type == 1): # data packet
  39. # send ACK, record snum, increment expected
  40. sock.sendto(packet.create_ack(snum).get_udp_data(), (haddr, dport))
  41. confirmed = snum
  42. expected = confirmed + 1
  43. # deal with new data
  44. msgfile.write(packet.data)
  45. elif (confirmed): # got wrong packet, send confirmation only of last good packet
  46. sock.sendto(packet.create_ack(confirmed).get_udp_data(), (haddr, dport))
  47. arrlog.close()