我是Python的新学习者。作为家庭作业问题的一部分,我试图计算客户端程序发送的每个数据包的RTT。我能够为客户端编写代码(在stackoverflow社区,Kudos的帮助下),我得到了每个成功数据包的RTT。我已成功计算出最大值,最小值和最小值。平均RTT。但RTT的中位数不起作用。我试图调用函数中位数,它不起作用。给我一个错误: IndexError:列表索引超出范围你能帮我吗?以下是客户端代码:
from socket import *
import datetime
import time
port=input('Port: ')
mylist=[]
def main():
serverName = 'localhost'
#port = 2015
Csocket = socket(AF_INET, SOCK_DGRAM)
message =' ping' # Client's message to the server
#data = input("Enter a message in lowercase")
LastPing = 12 #12 ping messages to be sent
count = 0
Csocket.settimeout(1) #timeout after one second
#print ("Attempting to send " , count , "messages" )
while count < LastPing: #while attempting to send to 12 times
count = count + 1 #incrementing the counter
startTime = time.time() # Start time when the message from the client is being sent
print(message , startTime , count) # Printing the clien't message as per required format
Csocket.sendto(message, (serverName, port)) #sends the message in the socket
try:
newmsg, address = Csocket.recvfrom(1024) # Reply message from server in uppercase form
RTT = ((time.time()) - startTime) #Calculating the Round Trip Time for each packet
mylist.append(RTT)
a = sum(mylist)
b = len(mylist)
average=a/b
print "Uppercase Message from the Server: ", newmsg
print "The Round Trip Time is: " + str(RTT) + " seconds"
except timeout:
print" Client's Request timed out\n"
except Exception as e:
print e
print "The program is done"
print "Stored RTTs are: ", mylist
print "Total number of successful packets is: ",b
print "Max RTT is: ",str(max(mylist)) + " seconds"
print "Min RTT is: ",str(min(mylist)) + " seconds"
print "Sum of all RTTs is: ",str(a) + " seconds"
print "Average Round Trip Time is: ",average
#def median(mylist):
sortedLst = sorted(mylist)
lstLen = len(mylist)
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0
print "Median RTT is: " (mylist) + "seconds"
Csocket.close
#median(mylist)
main()