-
Notifications
You must be signed in to change notification settings - Fork 0
/
transmitter.py
100 lines (81 loc) · 2.44 KB
/
transmitter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
############################################
# File name: Transmitter (transmitter.py) #
# Author: Jackie Ye & Reymon Mercado #
# Assignment: FINAL PROJECT for COMP 7005 #
# Instructor: Aman Abdulla #
############################################
import socket
import sys
import MyPacket
import MySocket
import config
import pickle
import time
# Creates a TCP/IP socketT
socketT = MySocket.mysocket()
socketT.sock.connect((config.hostnameNE, config.portA))
argument = sys.argv
def sendEot(connection, seqNum):
print "Sending FIN"
eot = MyPacket.mypacket(3, seqNum, None, config.windowSize, None)
eot = pickle.dumps(eot)
connection.sendall(eot)
with open(argument[1], 'r') as f:
seqNum = 1
resend = False
eotSent = False
cachePacket = []
while True:
# loops through the window
if eotSent == False:
for i in xrange(config.windowSize):
if resend:
# temp = pickle.loads(cachePacket[i])
# print "resending packets: %s" % (temp.seqNum)
time.sleep(0.01)
socketT.sock.sendall(cachePacket[i])
else:
read_data = f.read(1)
# pack data in packet
print 'sending packet. Sequence Number: %s. Type: %s' % (seqNum, 'Data')
packet = MyPacket.mypacket(2, seqNum, read_data, config.windowSize, None)
seqNum += 1
# encode packet
packet = pickle.dumps(packet)
# put packets in the cache array
cachePacket.append(packet)
# send encoded packet
socketT.sock.sendall(packet)
# reset variable after for loop
resend = False
try:
# set socket timeout for receiving ack
socketT.sock.settimeout(0.01)
# wait and receive ack
ack = socketT.sock.recv(config.BUFFER_SIZE)
except socket.error, e:
err = e.args[0]
# if timed out, that means ack is not received
if(err == 'timed out'):
resend = True
print "Time out. No ACK received, sending previous window again"
pass
else:
if ack:
# decode ack
recvAck = pickle.loads(ack)
print "ack received, ACK Number: %s" % (recvAck.ackNum)
# if ACK is EOT, it is a FIN ACK
if recvAck.type == 3:
print "FIN ACK received, closing connection"
socketT.sock.close()
break
if resend == False:
# reset cache packet array if resend is false
cachePacket = []
if not read_data and resend == False:
print "------ end of the file -------"
eotSent = True
if eotSent:
sendEot(socketT.sock, seqNum)
f.closed