【问题标题】:Sending Client Data With a Timer使用计时器发送客户端数据
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 所以,我理解...但是它是否与“尝试连接 1 秒,之后超时”是一回事,我觉得这是两个不同的东西,或者我可能只是想多了
    • 也许我不理解这个问题。我看到您的程序尝试连接到服务器,但如果没有,它会再尝试两次。我解释你要求的是一种在尝试之间等待 x 秒的方法,因为某种原因(也许给服务器更多的时间来初始化)。这是正确的吗?
    猜你喜欢
    • 2012-10-13
    • 2015-02-10
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 2016-07-21
    • 2014-04-08
    • 2013-02-01
    相关资源
    最近更新 更多