服務器端
import random from socket import * serverSocket = socket(AF_INET, SOCK_DGRAM)#建立udp協議的socket連接 serverSocket.bind(('', 12000)) while True: rand = random.randint(0, 10)#生成隨機數,模擬udp環境下的丟包 message, address = serverSocket.recvfrom(1024)#接收客戶端發送的信息,應該傳送ip地址比較好 message = message.upper() if rand < 4: continue#如果隨機數字小于4那么就模擬丟包,不進行回復 serverSocket.sendto(message, address) 客戶端
from socket import * import time HOST = 'localhost' PORT = 12000 clientSocket = socket(AF_INET, SOCK_DGRAM)#使用udp協議 clientSocket.bind(('', 6000))#綁定端口6000, 也可以不綁定 for i in range(0,10):#發出十次ping try: start_time = time.time()#從發出報文開始計時 clientSocket.sendto('A',(HOST, PORT))#發送報文給服務器 clientSocket.settimeout(1.0)#設置socket等待時間 message, address = clientSocket.recvfrom(1024)#recvfrom設置了一秒的時間限制 end_time = time.time()#結束時間 print "Ping %d %f"%(i, end_time-start_time)#得到ttl,并顯示出來 except timeout:#如果超過時間,拋出一個timeout的錯誤 print "Resquest time out" 以上這篇使用python編寫udp協議的ping程序方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答