测试此UDP套接字Python代码:奇怪的延迟; Windows与Linux

问题描述

我正在以1ms的间隔发送数据,但是在接收端,我似乎一次收到15-16个数据包,然后在15-16 ms延迟后接收另一组数据包。

请尝试以下代码,看看是否有相同的结果。我正在使用Windows 10计算机。我已经尝试了2个相同的结果。任何见识将不胜感激。

# -*- coding: utf-8 -*-
"""
Created on Thu Sep  3 23:32:44 2020

@author: Pratyush
"""

# sender.py
import socket
from time import sleep,monotonic_ns

TEMPO = 1e6
send = socket.socket(socket.AF_INET,socket.soCK_DGRAM)
last_second = monotonic_ns()
iteration_count = 0
while iteration_count < 1000:
    if monotonic_ns() >= last_second + TEMPO:
        last_second += TEMPO
        send.sendto(bytes(32),('127.0.0.1',8208))       
        iteration_count += 1

接收方代码如下,首先运行receiver.py

# -*- coding: utf-8 -*-
"""
Created on Thu Sep  3 23:32:13 2020

@author: Pratyush
"""

# receiver2.py
import socket
import time
"""
just get the raw values from UDP socket every 1ms
The sender sends it with that temporal resolution

"""

UDP_IP = ""
UDP_PORT = 8208 #UDP phasor values 32 bytes (V,phi,P)
sock_ph = socket.socket(socket.AF_INET,# Internet
                     socket.soCK_DGRAM)  # UDP
sock_ph.bind((UDP_IP,UDP_PORT))
print("socket bound,waiting for data...")

while True:
    time_before_raw = time.monotonic_ns()
    raw = sock_ph.recv(32) #I am receiving 32 bytes data
    time_after_raw = time.monotonic_ns()
    # print((time_after_raw-time_before_raw),raw,len(raw))
    print((time_after_raw-time_before_raw),len(raw))

我收到的结果如下:

0 32
0 32
16000000 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
15000000 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32

解决方法

根据PEP,Windows的单调时钟的分辨率为15mS。很有可能是您在输出中看到的粒度。

https://www.python.org/dev/peps/pep-0564/#id23