我遇到的问题是我的聊天客户端应该在服务器发送时从服务器接收和打印数据,然后允许客户端回复。
这很好,除了在提示客户端回复时整个过程停止。因此,在您输入内容之前,消息会堆积起来,然后在您执行此操作后,它会打印所有收到的消息。
不确定如何解决这个问题,所以我决定为什么不让客户有时间在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()
答案 0 :(得分:0)
我们可以使用相同的信号。我认为以下示例对您有用。
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"