簡體   English   中英

Python UDP插座; 當源停止時仍然接收數據; 為什么?

[英]Python UDP socket; still receiving data when source is stopped; why?

我每 1ms 向這個套接字發送 32 個字節的數據包。 我希望每 40 毫秒后打印一次數據。 顯然代碼就是這樣做的。 但即使我停止發送數據,我仍然繼續看到正在打印數據。 它是否將數據保存在某個緩存中? 或者只是 python 插座有很大的延遲? 為什么?

代碼如下:

## Import necessary libraries
import math
import numpy as np
import socket
import struct
import time
from synchrophasor.frame import CommandFrame
from datetime import datetime


## Configure socket for Phasor data ##

UDP_IP = "10.10.114.22"
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:

    raw = sock_ph.recv(32)
    #print(raw)
    mag = struct.unpack('d', raw[8:16])[0]
    # print("mag =",mag,type(mag))
    angle = struct.unpack('d', raw[16:24])[0]
    # print("angle =",angle,type(angle))
    header = struct.unpack('d', raw[0:8])[0]
    # print("header =",header,type(header))
    phasor = (mag, angle)
  
    Vol_A=raw
    VA = float(mag)
    phi_A = float(angle)
    VB = VA
    phi_B = phi_A+(math.pi) * 2 / 3
    VC = VA
    phi_C = phi_A-(math.pi) * 2 / 3
    time.sleep(1/25)
    # pmu.send_data(phasors=[(VA,phi_A),(VB,phi_B),(VC,phi_C)],analog=[9.91],digital=[0x0001])
    #time.sleep(1/config_rr)
    print([(VA,phi_A),(VB,phi_B),(VC,phi_C),datetime.now()])

大多數程序不想丟棄未讀數據報,因此大多數操作系統會為您緩沖它們。 您的情況有些不尋常,因此您需要編寫代碼來處理這種情況。 我會更改您的代碼以執行以下操作:

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 8208))

# block until we read an initial packet
raw = s.recv(1024)
s.setblocking(False)

while True:
    # unpack
    header, mag, angle = struct.unpack('ddd', raw)

    # do something with data
    print(f'header={header} mag={mag} angle={angle}')

    # sleep for some time
    time.sleep(1/25)

    # discard any packets you've received in the mean time
    while True:
        try:
            raw = s.recv(1024)
        except OSError as err:
            # OS buffer is empty: we've therefore got the most recent data
            if err.errno == socket.EWOULDBLOCK:
                break
            # something else failing, reraise the error
            raise

請注意,Steffen Ullrich 建議以正確的速率發送數據會更容易,但假設您可以控制發送過程。 您說“我正在發送”的事實表明您這樣做了,因此可能會做出更好的解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM