在Python中测量socket到socket的延迟

2024-04-25 01:14:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用pythonsocket库向另一个服务器发送消息并测量往返延迟。我是一个新的网络,所以它非常基础,只使用socket文档(http://wiki.python.org/moin/UdpCommunication)中给出的send-receive示例。目前我正在使用时间。时间()为消息发出和返回的时间戳,但我希望最终能够获得纳秒级的精度。现在,我通过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回来的脚本

^{pr2}$

这是在被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

Tags: ip脚本消息messageport时间socketping