使用 python 脚本从本地网络进行 UDP 广播失败

问题描述 投票:0回答:1

我在小型本地网络上有一台 Windows 计算机,其中包含 LTE 路由器、托管交换机、Windows 盒子和通过 UDP 广播位置数据的 GNSS 设备。 GNSS 设置为在 255.255.255.255 : 5017 上广播

我还有一个带有两个以太网接口的 Windows 设备,我在该设备上运行以下 python 脚本来尝试接收这些 UDP 消息并将它们写入文件。

import os
import socket
import pynmea2
import datetime
from io import StringIO

path = "C:\\DataGoesHere\\"

IP = " "
port = 5017

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(5)
sock.bind((IP,port))

while True:
    today = datetime.date.today().strftime("%Y%m%d")
    todayfile = f'{today}_GNSS.csv'
    

    pathfile = os.sep.join([path, todayfile])
    if not os.path.isfile(pathfile):
        with open(pathfile, 'w') as file:
            print('Created file: {}'.format(pathfile))
            #pass

    with open(pathfile, 'a') as file:
        while today==datetime.date.today().strftime("%Y%m%d"):
            try:
                data = sock.recv(4096)
                print(pynmea2.parse(data.decode()))
                file.write(data.decode())
            except socket.timeout:
                print("Didn't receive data! [Timeout]")

到目前为止,我总是遇到套接字超时。我可以使用wireshark查看UDP数据包,因此它们正在发送并到达。我已经确保有一条防火墙规则允许端口 5017 上的 UDP 数据包,并且我还测试了暂时关闭 Windows 防火墙,以防仍然存在问题。即使防火墙关闭,脚本也会出现 socket.timeout 错误。

此时,我对如何排除故障的了解已经结束,并且希望得到任何修复或诊断提示。

python sockets networking udp
1个回答
0
投票

@RonMaupin 这给了我很好的指导。正在广播的设备只能选择使用 TCP,因此我改用 TCP 发送数据并切换套接字类型,现在一切正常。所以它实际上并没有解决我在这里问的问题,但总的来说我可能正在以更好的方式做事。

© www.soinside.com 2019 - 2024. All rights reserved.