Reputation: 51
I want to have a thread that waits for a UDP packet in background and while the packet is not received I want the script be able to do another things. But when I start the thread the script waits for an UDP packet and stop.
import threading
import socket
def rec_UDP():
while True:
# UDP commands for listening
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('10.0.0.15', UDP_PORT))
data, addr = sock.recvfrom(1024)
print "received message:", data
return data
# The thread that ables the listen for UDP packets is loaded
listen_UDP = threading.Thread(target=rec_UDP())
listen_UDP.start()
data = 'Nothing received'
while True:
print 'The packet received is: ' + data
Upvotes: 5
Views: 8832
Reputation: 337
This doesn't work for Python 3, but it set me on the right path. here's my Python 3 version.
#!/usr/bin/python3
import _thread, time, socket
data = '' # Declare an empty variable
# UDP setup for listening
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', 12345)) # I'm using port 12345 to bind to
# Define a function for the thread
def listening_thread():
global data # data needs to be defined as global inside the thread
while True:
data_raw, addr = sock.recvfrom(1024)
data = data_raw.decode() # My test message is encoded
print ("Received message inside thread:", data)
try:
_thread.start_new_thread(listening_thread, ())
except:
print ("Error: unable to start thread")
quit()
while 1:
print ('Now I can do something useful while waiting in the main body.')
if data:
print ('THE PACKET RECEIVED BY THE MAIN BODY IS: ' + data)
data = '' # Empty the variable ready for the next one
time.sleep(2)
Upvotes: 1
Reputation: 369274
By appending ()
after the function, the code calls the function directly and therefore blocking the main thread instead of running the function in a separated thread.
Remove the ()
after the function name.
listen_UDP = threading.Thread(target=rec_UDP)
Upvotes: 3