"""
 This program read data from a TEXT file and do the following:
	a. It measure the elapsed time of the file read;
	b. It sends the data over a socket to a server, 
	wait to receive the data back from the server, and measure
	the elapsed time (that is, the round trip time).
	Author: T. A. Yang
	Date: 9/25/2024
"""
from socket import *
import time
serverName = '127.0.0.1'  #the loopback interface
#serverName = '192.168.254.121'  #a host on the same LAN
serverPort = 12000

for count in range(0,5):    #run n times and get the average
     print("experiment %d ----------------------------------------------" % (count))
     clientSocket = socket(AF_INET, SOCK_STREAM)
     clientSocket.connect((serverName,serverPort)) 
     # Instead, read the data from a file and measure the elapsed time
     print("Reading data from file")
     frStart = time.time()
     with open("testData5.txt","r") as file:
          sentence = file.read()
     frEnd = time.time()
     size = len(sentence)
     print("%d bytes read from the file" % (size))
     print(">>>>> elapsed time of file read: %f" % (frEnd-frStart))

     # start measuring the elapsed time of network round trip
     start = time.time()
     clientSocket.send(sentence.encode())
     modifiedSentence = clientSocket.recv(50000)
     end = time.time()
     sizeReceived = len(modifiedSentence)
     #print('From Server: ', modifiedSentence.decode())
     #print("start transmission time: %f" % (start))
     print('%d %s' % (size, ' bytes sent to the server.'))
     #print("end time: %f" % (end))
     print('%d %s' % (sizeReceived, ' bytes received from the server.'))
     print('>>>>> round trip time (RTT) = %f' % (end-start))
     clientSocket.close()