【发布时间】:2013-03-09 22:17:07
【问题描述】:
我遇到的问题是我的聊天客户端应该在服务器发送数据时从服务器接收并打印数据,然后允许客户端回复。
这工作正常,除了提示客户端回复时整个过程停止。因此,消息会堆积起来,直到您输入某些内容,然后在您输入内容之后,它会打印所有收到的消息。
不知道如何解决这个问题,所以我决定为什么不让客户有时间在 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()
【问题讨论】:
-
你为什么用
input而不是raw_input?input隐式使用和eval,因此它违反直觉且不安全。如果你想要一个字符串,你应该使用raw_input。 -
@Kyle Strand 不能在 Python 3.1 或我使用的版本中使用 raw_input。你能解释一下风险吗?我从来不知道为什么人们说不要使用它。
-
啊,抱歉,没有意识到您使用的是 Python 3,其中
input替换了 Python 2 的raw_input,并且没有对应的(据我所知)Python 2 的不安全 @ 987654331@. -
你需要两个线程。一个将从服务器读取数据并将其写入屏幕,另一个将从用户读取输入并将其发送到服务器。在文档中查找
threading模块。 -
我无法测试该代码,因为我没有服务器,但这里有一个示例证明您可以使用两个线程同时读写:pastebin.com/u86Gf8L4 问题必须在其他地方。
标签: python function python-3.x timeout