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

问题描述:

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

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 
+1

您可以从多个来源收到http://*.com/questions/15101333/is-there-a-way-to-listen-to-multiple-python-sockets-at-once – Kafo

+1

谢谢!我应该研究更多,因为有人已经问过同样的问题 – tedhan

+0

不客气。 – Kafo

如果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源进行测试。

+0

我很欣赏代码,我尝试使用select,它确实与超时参数一起工作,使用列表时出现了一些问题,但它已修复,再次感谢! – tedhan