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

2024-05-12 12:32:59 发布

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

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

请尝试这段代码,看看是否有相同的结果。我使用的是Windows10机器。我在两台电脑上试过,结果都一样。如有任何见解,将不胜感激

# -*- 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

Tags: pyimportrawbytestimecountsocketsock