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

标签 python multithreading python-2.7 background udp

我想要一个在后台等待 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)

关于python - 在后台接收 UDP 数据包(PYTHON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26846988/

相关文章:

python - 如何使用 mlflow.pyfunc.log_model() 使用 Keras 步骤记录 sklearn 管道?类型错误 : can't pickle _thread. RLock 对象

python - 从 networkx 中的文件中读取具有 pos 属性的节点

Python 解释器阻止多线程 DNS 请求?

python - 在多线程 Python 中使用队列,将队列作为引用传递给子函数

python - 遍历列表长度并创建函数列表

memory - file.read() 在 64 位 python 上返回超过 2 GB 时出错

python-2.7 - 类型错误 : softmax() got an unexpected keyword argument 'axis'

python - 仅在二级索引上的 Pandas 多索引切片

python - 如何在加载关系时指示SQLAlchemy ORM 并行执行多个查询?

c++ - 同时对象调用