作业2: UDP ping程序
官方给的服务端端代码:
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)发送10个ping的报文到服务器, 格式是:Ping 序号 时间
2) 打印服务器返回的报文
3)计算每个返回报文的RTT时间(往返时间),并打印
4)每个报文的等待服务器回答时间至多1秒,超时则打印报文丢失
因为UDP是非可靠的数据传输协议,我们使用随机数来模拟数据包丢失,设置一个1s的超时响应。
UDPPingClient.py
import time
from socket import *
serverName = '10.21.2.185' # 主机
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
clientSocket.settimeout(1) # 设置超时
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 # 计算往返时间
print('Sequence %d: Reply from %s, RTT = %fs' % (i+1, serverName, rtt))
except Exception as e:
print('Sequence %d: Request timed out' % (i+1)) # 处理异常
# 关闭链接
clientSocket.close()
运行:
1)打开一个终端运行 python3 UDPPingServer.py 或者 python UDPPingServer.py (python2.x, python3.x其实都可以)
2)打开另外一个终端运行 python3 UDPPingClient.py 或者 python UDPPingClient.py
结果如下:
UDPPingServer.png
UDPPingClient.png
计算所有报文往返时间的最大值、最小值、平均值及丢包率
实现UDP Heartbeat(客户端和服务器端)
练习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()
练习2:
超标了,目前不会做 ( ̄ー ̄)