Python网络编程——设定并获取默认的套接字超时时间

2023-06-12,,

Sometimes,you need to manipulate the default values of certain properties of a socket library, for example, the socket timeout.

设定并获取默认的套接字超时时间。

1.代码

 import socket

 def test_socket_timeout():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Default socket timeout: %s" % s.gettimeout())
# 获取套接字默认超时时间
s.settimeout(100)
# 设置超时时间
print("Current socket timeout: %s" % s.gettimeout())
# 读取修改后的套接字超时时间 if __name__ == '__main__':
test_socket_timeout()

2. AF_INET和SOCK_STREAM解释

     # 地址簇
# socket.AF_INET IPv4(默认)
# socket.AF_INET6 IPv6
# socket.AF_UNIX 只能够用于单一的Unix系统进程间通信 # socket.SOCK_STREAM(数据流) 提供面向连接的稳定数据传输,即TCP/IP协议.多用于资料(如文件)传送。

3.gettimeout()和settimeout()解释

 def gettimeout(self):  # real signature unknown; restored from __doc__
"""
gettimeout() -> timeout Returns the timeout in seconds (float) associated with socket
operations. A timeout of None indicates that timeouts on socket
operations are disabled.
"""
return timeout def settimeout(self, timeout): # real signature unknown; restored from __doc__
"""
settimeout(timeout) Set a timeout on socket operations. 'timeout' can be a float,
giving in seconds, or None. Setting a timeout of None disables
the timeout feature and is equivalent to setblocking(1).
Setting a timeout of zero is the same as setblocking(0).
"""
pass
# 设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。
# 一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如 client 连接最多等待5s )

4.运行结果

 Default socket timeout: None
Current socket timeout: 100.0

Python网络编程——设定并获取默认的套接字超时时间的相关教程结束。

《Python网络编程——设定并获取默认的套接字超时时间.doc》

下载本文的Word格式文档,以方便收藏与打印。