Python UDP communication using Socket, check data received
<p>I'm pretty new to the Python, trying to write a code to receive string from UDP connection, the problem I have now is that I need to receive data from 2 sources, I want the program continue looping if there is no data from either or both of them, but now if there is no data from source 2, it will stop there and wait for the data, how to solve it?
I was thinking about using if statement, but I don't know how to check if the incoming data is empty of not, any ideas will be appreciated!</p>

<pre><code>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
</code></pre>

<p>If <a href="https://docs.python.org/2/library/select.html" rel="nofollow">select</a> 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 <a href="https://docs.python.org/2/library/threading.html#threading.Lock" rel="nofollow">threading.Lock</a> for help there.</p>

<pre><code>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)
</code></pre>

<p><em>Note this wasn't tested due not having two UPD sources running.</em></p>

python sockets udp