【问题标题】:Certain time to wait for socket connection等待套接字连接的一定时间
【发布时间】:2021-05-23 05:46:59
【问题描述】:

我尝试制作一个脚本,用 *python-socket 连接到服务器。

# connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# in this case socket.socket() is more clearer 
connection = socket.socket()
connection.connect((ip, port))

但是当 ip 或端口不正确时,它会尝试永远连接。 那么如何实现一定的时间来等待服务器响应/连接呢?例如5秒后服务器无法访问,连接将关闭,并显示服务器无法访问/离线的错误。

【问题讨论】:

  • 即使没有settimeout,如果 IP 存在但端口不存在,connect 在 2-3 秒内失败 (ConnectionRefusedError),如果 IP 不存在,则在大约 20 秒内 (TimeoutError)不存在,至少在我的 Windows 系统上。你等了多久?
  • 大约 10 秒

标签: python-3.x sockets server


【解决方案1】:

要指定等待服务器的特定时间,您只需这样做:

connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.settimeout(5)  # waits 5 sec until the connection will be closed
connection.connect((ip, port))
connection.settimeout(None)  #sets the timeout to None (important)

在此示例中,连接将等待 5 秒,直到引发异常,因为时间已经结束。您可以在 try 语句中使用“except socket.timeout:”简单地捕获此异常

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2010-11-25
    • 2012-04-15
    相关资源
    最近更新 更多