Assignment 2: UDP Pinger[課後作業]
阿新 • • 發佈:2018-05-24
generate baidu sig sign uri aid ref gen 服務端
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
Assignment 2: UDP Pinger[課後作業]