【Socket程式設計】Python用udp實現簡易ping
阿新 • • 發佈:2019-02-17
用Python實現一個簡易的ping程式,客戶端傳送一個簡易的ping報文,接收到該資訊的伺服器返回對應的pong報文,然後客戶端計算RTT。由於UDP不是可靠協議,需要為該程式設定超時機制,超時1秒後將假設報文沒有收到,並打印出超時提示。
伺服器實現如下:
import socket import errno import os HOST, PORT = "", 8888 def serve_forever(): listen_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_socket.bind((HOST, PORT)) print "Serving on port %s ..." % PORT while True: request, addr = listen_socket.recvfrom(2048) response = "Wrong CMD" if request == "Ping": #保證是Ping指令,否則返回Wrong CMD response = "Pong" listen_socket.sendto(response, addr) if __name__ == '__main__': serve_forever()
客戶端如下:
這裡使用 settimeout() 設定超時時間,使用當 ping-pong 的過程超過1秒後會出現 socket.timeout 異常,此時會進入 socket.timeout 分支。import socket import datetime #使用datetime計算時間差 SERVER_ADDRESS = 'localhost', 8888 REQUEST = "Ping" def main(): i = 10 while i > 0: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(1) try: begin_time = datetime.datetime.now() sock.sendto(REQUEST, (SERVER_ADDRESS)) while True: data, addr = sock.recvfrom(2048) if data == "Pong": end_time = datetime.datetime.now() i = i - 1 break else: print(data) continue except socket.timeout: print "time out" else: msec = (end_time - begin_time).microseconds / 1000.0 print "rtt: %f msec" % msec if __name__ == '__main__': main()