Python 使用Socket的UDP通信,检查收到的数据

Python UDP communication using Socket, check data received

我是 Python 的新手,正在尝试编写代码以从 UDP 连接接收字符串,我现在遇到的问题是我需要从 2 个源接收数据,我想要程序如果其中一个或两个都没有数据,则继续循环,但是现在如果源2没有数据,它将停在那里等待数据,如何解决? 我正在考虑使用 if 语句,但我不知道如何检查传入数据是否为空或不是,任何想法将不胜感激!

import socket

UDP_IP1 = socket.gethostname()
UDP_PORT1 = 48901
UDP_IP2 = socket.gethostname()
UDP_PORT2 = 48902

sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock1.bind((UDP_IP1, UDP_PORT1))
sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock2.bind((UDP_IP2, UDP_PORT2))

while True:
    if sock1.recv != None:
        data1, addr = sock1.recvfrom(1024)
        data1_int = int(data1)
        print "SensorTag[1] RSSI:", data1_int

    if sock2.recv != None:
        data2, addr = sock2.recvfrom(1024)
        data2_int = int(data2)
        print "SensorTag[2] RSSI:", data2_int

如果select doesn't work out for you you can always throw them into a thread. You'll just have to be careful about the shared data and place good mutex around them. See threading.Lock在那里寻求帮助。

import socket
import threading
import time

UDP_IP1 = socket.gethostname()
UDP_PORT1 = 48901
UDP_IP2 = socket.gethostname()
UDP_PORT2 = 48902

sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock1.bind((UDP_IP1, UDP_PORT1))
sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock2.bind((UDP_IP2, UDP_PORT2))

def monitor_socket(name, sock):
    while True:
        sock.recv is not None:
            data, addr = sock.recvfrom(1024)
            data_int = int(data)
            print(name, data_int)
    
t1 = threading.Thread(target=monitor_socket, args=["SensorTag[1] RSSI:", sock1
t1.daemon = True
t1.start()
    
t2 = threading.Thread(target=monitor_socket, args=["SensorTag[2] RSSI:", sock2])
t2.daemon = True
t2.start()
    
while True:
    #  We don't want to while 1 the entire time we're waiting on other threads
    time.sleep(1)

请注意,由于没有两个 UPD 源 运行,因此未进行测试 运行。