Assignment 2: UDP Pinger[课后作业]

Computer Networking : A Top-Down Approach 的课后作业.

要求: 基于UDP协议,实现一个Pinger工具. 服务端代码已经提供了,自己实现客户端的代码.
完整的题目链接: https://wenku.baidu.com/view/ed19e6cce2bd960591c677d2.html

服务端代码:

# UDPPingerServer.py
# We will need the following module to generate randomized lost packets
import random
from socket import *
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bind(('127.0.0.1', 9600))
while True:
    # Generate random number in the range of 0 to 10
    print('Waiting for Client!')
    rand = random.randint(0, 10)
    # Receive the client packet along with the address it is coming from
    message, address = serverSocket.recvfrom(1024)
    print(message)
    # Capitalize the message from the client
    data = message.upper()# If rand is less is than 4, we consider the packet lost and do not respond
    if rand < 4:
        continue
    # Otherwise, the server responds
    serverSocket.sendto(data, address)

客户端代码

自己随手写的,还可以再完善下,也懒得改了,不过题目的基本要求已经达到了.

import time
from socket import *


server_address = ('127.0.0.1', 9600)
count = 0

message = b'python'
while count < 10:
    clientSocket = socket(AF_INET, SOCK_DGRAM)
    clientSocket.settimeout(1)
    clientSocket.sendto(message, server_address)
    start_time = time.clock()
    try:
        data, address = clientSocket.recvfrom(1024)
        if data:
            end_time = time.clock()
            print('Ping:', (end_time - start_time)*1000)
            print(data)
            count += 1
    except:
        continue

猜你喜欢

转载自www.cnblogs.com/crb912/p/9082379.html