Skip to main content
 首页 » 编程设计

python之如果未及时满足某个条件,则函数超时

2025年05月04日7exmyth

我遇到的问题是我的聊天客户端应该在服务器发送数据时从服务器接收和打印数据,然后允许客户端回复。

这工作正常,除了当提示客户端回复时整个过程停止。所以消息会堆积起来,直到你输入一些东西,在你输入之后,它会打印所有收到的消息。

不确定如何解决这个问题,所以我决定为什么不让客户有时间在 5 秒后输入回复超时,这样回复无论如何都可以通过。它有很大的缺陷,因为输入会自行重置,但无论如何它都能更好地工作。

下面是需要超时的函数:

# now for outgoing data 
def outgoing(): 
    global out_buffer 
    while 1: 
        user_input=input("your message: ")+"\n" 
        if user_input: 
            out_buffer += [user_input.encode()] 
#       for i in wlist: 
            s.send(out_buffer[0]) 
            out_buffer = [] 

我应该如何使用超时?我正在考虑使用 time.sleep,但这只会暂停整个操作。

我试着寻找文档。但是我没有找到任何可以帮助我使程序计数达到设定限制然后继续的东西。

关于如何解决这个问题有什么想法吗? (不需要使用超时,只需要在发送客户端回复之前停止消息堆积)(感谢所有帮助我走到这一步的人)

对于 Ionut Hulub:

from socket import * 
import threading 
import json 
import select 
import signal # for trying to create timeout 
 
 
print("client") 
HOST = input("connect to: ") 
PORT = int(input("on port: ")) 
 
# create the socket 
s = socket(AF_INET, SOCK_STREAM) 
s.connect((HOST, PORT)) 
print("connected to:", HOST) 
 
#--------- need 2 threads for handling incoming and outgoing messages-- 
 
#       1: create out_buffer: 
out_buffer = [] 
 
# for incoming data 
def incoming(): 
    rlist,wlist,xlist = select.select([s], out_buffer, []) 
    while 1: 
        for i in rlist: 
            data = i.recv(1024) 
            if data: 
                print("\nreceived:", data.decode()) 
 
# now for outgoing data 
def outgoing(): 
    global out_buffer 
    while 1: 
        user_input=input("your message: ")+"\n" 
        if user_input: 
            out_buffer += [user_input.encode()] 
#       for i in wlist: 
            s.send(out_buffer[0]) 
            out_buffer = [] 
 
thread_in = threading.Thread(target=incoming, args=()) 
thread_out = threading.Thread(target=outgoing, args=()) 
thread_in.start() # this causes the thread to run 
thread_out.start() 
thread_in.join()  # this waits until the thread has completed 
thread_out.join() 

请您参考如下方法:

我们可以使用信号。我认为下面的示例会对您有用。

import signal 
 
def timeout(signum, frame): 
    raise Exception 
 
#this is an infinite loop, never ending under normal circumstances 
def main(): 
    print 'Starting Main ', 
    while 1: 
        print 'in main ', 
 
#SIGALRM is only usable on a unix platform 
signal.signal(signal.SIGALRM, timeout) 
 
#change 5 to however many seconds you need 
signal.alarm(5) 
 
try: 
    main() 
except: 
    print "whoops"