作業(yè)2: UDP ping程序
官方給的服務(wù)端端代碼:
UDPPingServer.py
import random
from socket import *
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', 12000))
while True:
rand = random.randint(0, 10)
message, address = serverSocket.recvfrom(1024)
message = message.upper()
if rand < 4:
continue
serverSocket.sendto(message, address)
需要自己編寫客戶端代碼蹄衷,要求
1)發(fā)送10個(gè)ping的報(bào)文到服務(wù)器睦番, 格式是:Ping 序號(hào) 時(shí)間
2) 打印服務(wù)器返回的報(bào)文
3)計(jì)算每個(gè)返回報(bào)文的RTT時(shí)間(往返時(shí)間)托嚣,并打印
4)每個(gè)報(bào)文的等待服務(wù)器回答時(shí)間至多1秒,超時(shí)則打印報(bào)文丟失
因?yàn)閁DP是非可靠的數(shù)據(jù)傳輸協(xié)議,我們使用隨機(jī)數(shù)來模擬數(shù)據(jù)包丟失矩父,設(shè)置一個(gè)1s的超時(shí)響應(yīng)攻柠。
UDPPingClient.py
import time
from socket import *
serverName = '10.21.2.185' # 主機(jī)
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
clientSocket.settimeout(1) # 設(shè)置超時(shí)
for i in range(0, 10):
sendTime = time.time()
message = ('Ping %d %s' % (i + 1, sendTime)).encode()
try:
clientSocket.sendto(message, (serverName, serverPort)) # 發(fā)送數(shù)據(jù)
modifiedMessage, serverAddress = clientSocket.recvfrom(2048) # 接收服務(wù)器的響應(yīng)
rtt = time.time() - sendTime # 計(jì)算往返時(shí)間
print('Sequence %d: Reply from %s, RTT = %fs' % (i+1, serverName, rtt))
except Exception as e:
print('Sequence %d: Request timed out' % (i+1)) # 處理異常
# 關(guān)閉鏈接
clientSocket.close()
運(yùn)行:
1)打開一個(gè)終端運(yùn)行 python3 UDPPingServer.py
或者 python UDPPingServer.py
(python2.x, python3.x其實(shí)都可以)
2)打開另外一個(gè)終端運(yùn)行 python3 UDPPingClient.py
或者 python UDPPingClient.py
結(jié)果如下:
計(jì)算所有報(bào)文往返時(shí)間的最大值士八、最小值、平均值及丟包率
實(shí)現(xiàn)UDP Heartbeat(客戶端和服務(wù)器端)
練習(xí)1:
from socket import *
import time
serverName = '10.21.2.185'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
timeout = 1
clientSocket.settimeout(timeout)
rttTimes = []
failPing = 0
for i in range(0, 10):
sendTime = time.time()
message = ('Ping %d %s' % (i + 1, sendTime)).encode()
try:
clientSocket.sendto(message, (serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
rtt = time.time() - sendTime
rttTimes.append(rtt)
print('Sequence %d: Reply from %s, RTT = %fs' % (i+1, serverName, rtt))
except Exception as e:
failPing = failPing + 1
rttTimes.append(timeout)
print('Sequence %d: Request timed out' % (i+1))
maxTime = max(*rttTimes)
minTime = min(*rttTimes)
sumTime = 0
for x in range(len(rttTimes)):
sumTime += rttTimes[x]
avgTime = sumTime / len(rttTimes)
loseRate = failPing / 10.0 * 100
print('The minimum RTT: %fs \nThe maximum RTT: %fs \nThe average RTT: %fs' % (minTime, maxTime, avgTime))
print('The packet loss rate: %.2f%%' % (loseRate))
clientSocket.close()
練習(xí)2:
超標(biāo)了哮翘,目前不會(huì)做 ( ̄ー ̄)