2016-09-20 31 views
0

我對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://stackoverflow.com/questions/15101333/is-there-a-way-to-listen-to-multiple-python-sockets-at-once – Kafo

+1

謝謝!我應該研究更多,因爲有人已經問過同樣的問題 – tedhan

+0

不客氣。 – Kafo

回答

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源進行測試。

+0

我很欣賞代碼,我嘗試使用select,它確實與超時參數一起工作,使用列表時出現了一些問題,但它已修復,再次感謝! – tedhan