【发布时间】:2019-01-29 21:43:08
【问题描述】:
所以我有一个简单的客户端-服务器。
它们与命令行参数正确连接,发送和接收数据。
当服务器未启动并运行但客户端执行时:尝试连接,1 秒后显示超时(3 次)消息,然后关闭。
我能达到的最接近的方法就是尝试 3 次。
import sys
from socket import *
# Get the server hostname, port and data length as command line arguments
argv = sys.argv
host = argv[1]
port = argv[2]
count = argv[3]
# Command line argument is a string, change the port and count into integer
port = int(port)
count = int(count)
data = 'X' * count # Initialize data to be sent
# Create UDP client socket. Note the use of SOCK_DGRAM
clientsocket = socket(AF_INET, SOCK_DGRAM)
# Sending data to server
# times out after 1 second (?)
for i in range(3):
try:
print("Sending data to " + host + ", " + str(port) + ": " + data)
clientsocket.sendto(data.encode(),(host, port))
# Receive the server response
dataEcho, address = clientsocket.recvfrom(count)
# Display the server response as an output
print("Receive data from " + address[0] + ", " + str(address[1]) + ": " + dataEcho.decode())
break
except:
print("timed out")
finally:
#Close the client socket
clientsocket.close()
如何添加计时器?只需在每次尝试之间增加 1 秒,而不是我的编码方式。
【问题讨论】:
标签: python server client client-server