Ric*_*ñoz 5 python multithreading udp background python-2.7
我想要一个线程在后台等待 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
Run Code Online (Sandbox Code Playgroud)
()通过在函数后面追加,代码可以直接调用该函数,从而阻塞主线程,而不是在单独的线程中运行该函数。
去掉()函数名后面的 。
listen_UDP = threading.Thread(target=rec_UDP)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8384 次 |
| 最近记录: |