使用计时器发送客户端数据

时间:2019-01-29 21:43:09

标签: python server client client-server

所以我有一个简单的客户端服务器。

它们正确连接了命令行参数,发送和接收数据。

当服务器未启动并运行但客户端执行时:尝试连接,显示消息在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秒,而不是我的编码方式。

1 个答案:

答案 0 :(得分:1)

如果您只想让程序休眠x秒,则可以import time,然后在time.sleep(num_of_seconds_to_sleep)行之后添加clientsocket.close()