python udp socket 包接收超时_Python中UDP套接字超时

在Python中处理UDP套接字接收超时问题,可以使用自定义的timeout类,通过创建线程和设置超时回调实现。当超过预设时间限制,线程会被强制终止,并抛出TimeoutReached异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果你找不到其他解决方案,你可以尝试使用这个超时修饰符,这是我不久前写的。检查是否有效import ctypes

import threading

import time

class timeout:

def __init__(self, timeout, kill_on_timeout=True):

self.__timeout = timeout

self.__kill_on_timeout = kill_on_timeout

def __call__(self, func):

def prep_func(*args, **kwargs):

result = args[0]

args = tuple(list(args)[1:])

try:

result.append(func(*args, **kwargs))

except Exception as e:

result.append(e)

def timeout_func(*args, **kwargs):

result = []

args = tuple([result]+list(args))

t = threading.Thread(target=prep_func, args=args, kwargs=kwargs)

t.daemon = True

t.start()

timeout_time = self.__timeout+time.time()

while True:

if time.time()>=timeout_time:

if self.__kill_on_timeout:

try:

terminate_thread(t)

except:

raise TimeoutReached('Could not kill the thread!')

raise TimeoutReached('Timeout reached! Thread killed.')

if result:

if not issubclass(type(result[0]), BaseException):

return result[0]

raise result[0]

time.sleep(0.001)

return timeout_func

def terminate_thread(thread):

if not thread.isAlive():

return None

exc = ctypes.py_object(SystemExit)

res = ctypes.pythonapi.PyThreadState_SetAsyncExc(

ctypes.c_long(thread.ident), exc)

if res == 0:

raise ValueError('err')

elif res > 1:

ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)

raise SystemError('err')

class TimeoutReached(Exception):

pass

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值