在后台接收UDP数据包(PYTHON)



我希望有一个线程在后台等待UDP数据包,当数据包没有收到时,我希望脚本能够做其他事情。但当我启动线程时,脚本会等待UDP数据包并停止。

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

通过在函数后面附加(),代码直接调用函数,从而阻塞主线程,而不是在单独的线程中运行函数。

删除函数名称后的()

listen_UDP = threading.Thread(target=rec_UDP)

这对Python3不起作用,但它让我走上了正确的道路。这是我的Python 3版本。

#!/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)

最新更新