我想设置tcp服务器和客户端,其中服务器监视客户端输入,如果没有收到输入,则每3秒发送一次请求。然后客户回复其时间。这是无限循环的。而且,它们都可以选择退出无限循环。我不知道如何添加退出功能,因为send(),recv()和input()会阻止代码执行。
我尝试将select与3秒超时一起使用,但没有成功。我尝试了线程处理,但是在第一个用户输入之后直到下一个用户输入时,它都会停止。我希望它无限运行,除非用户想退出。
通信的无限循环:
客户端:
while True:
data = ClientSocket.recv(1024).decode()
print("From Server: " + str(data))
# clear string
data = ''
data = 'Random Number: ' + str(random.randint(1, 101))
current_time = datetime.now()
required_format = (current_time.strftime("Date: %Y-%m-%d\tTime: %H:%M:%S.%f")[:-3])
data = data + "\t" + required_format + '\n'
ClientSocket.send(data.encode())
print("Sending: " + str(data))
data = ''
服务器端:
while True:
data = ''
data = 'Please enter a response.'
print("Sending: " + str(data))
ClientSocket.send(data.encode())
# clear string
data = ''
data = ClientSocket.recv(1024).decode()
print("From Client: " + str(data))
选择我尝试过的功能:
readlist = [ClientSocket]
incoming = select.select(readlist, [], [], 3)
if incoming:
#perform a chat function here
else:
#use the code mentioned above for automated messages
这是我尝试过的线程功能: Python 3 Timed Input
在发送和接收消息请求和确认时,如何限制recv(),send()和input()的时间?
如果您想查看完整的代码,请告诉我。
答案 0 :(得分:0)
类似的事情应该对您有用
server.py
inputs = [server]
outputs = []
messages = {}
try:
while inputs:
readable, writable, error = select.select(inputs, outputs, [])
for sock in readable:
if sock is server:
client, _ = sock.accept()
inputs.append(client)
messages[client] = Queue()
else:
data = sock.recv(1024).decode()
if data and data != 'exit\n':
print(data)
messages[sock].put(data)
if sock not in outputs:
outputs.append(sock)
else:
print('Client disconnected')
sock.close()
inputs.remove(sock)
for sock in outputs:
try:
msg = messages[sock].get_nowait()
sock.send(msg.upper().encode())
except Empty:
sleep(3)
sock.send(b'No data recieved')
outputs.remove(sock)
except KeyboardInterrupt:
server.close()
client.py
inputs = [sock, sys.stdin]
while inputs:
readable, _, _ = select.select(inputs, [], [])
for s in readable:
if s is sock:
data = sock.recv(1024).decode()
if data:
if data.lower() != 'exit':
print('{}'.format(data))
sys.stdout.write('You: ')
sys.stdout.flush()
else:
exiting('Server')
else:
exiting('Server')
else:
msg = sys.stdin.readline()
sock.send(msg.encode())
sys.stdout.write('You: ')