我正在使用 Python 套接字库向另一台服务器发送消息并测量往返延迟。我是新网络,所以它非常基础,只需使用套接字文档(http://wiki.python.org/moin/UdpCommunication)中给出的发送接收示例。目前我正在使用 time.time() 来标记消息何时发出以及何时返回,尽管我希望最终能够获得纳秒级的精度。现在,我通过我的 python 脚本获得了大约 300 微秒,但从 shell ping 产生了大约 100 微秒。我可以做些什么来获得更快的沟通和/或更准确的测量?
发送一条消息的脚本:
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
print "SENT {0}".format(int(time.time()*1000*1000)
这是侦听 ping 返回的脚本
import socket
UDP_IP = "originating side localhost ip"
UDP_PORT = 9112
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
if data is not None:
print "received message: {0} {1}".format(data, int(time.time()*1000*1000)
这是在被 ping 的服务器上侦听的脚本。当它在端口上收到一条消息时,它会立即返回一条消息
import socket
UDP_IP = "pinged server's localhost ip"
UDP_PORT = 9111
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
UDP_IP2 = "ip of server that sent ping"
UDP_PORT2 = 9112
MESSAGE = "HEY"
sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print "Listening on PORT 9111"
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
if data is not None:
sock.sendto(MESSAGE, (UDP_IP2, UDP_PORT2))
print "received message: ", data