我是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
答案 0 :(得分:1)
如果select无法解决问题,您可以随时将它们放入线程中。您只需要小心共享数据并在它们周围放置好的互斥锁。请点击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 != 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源,因此未对此进行测试。