Sometimes,you need to manipulate the default values of certain properties of a socket library, for example, the socket timeout.
设定并获取默认的套接字超时时间。
1.代码
1 import socket 2 3 4 def test_socket_timeout(): 5 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 6 print("Default socket timeout: %s" % s.gettimeout()) 7 # 获取套接字默认超时时间 8 s.settimeout(100) 9 # 设置超时时间 10 print("Current socket timeout: %s" % s.gettimeout()) 11 # 读取修改后的套接字超时时间 12 13 14 if __name__ == ‘__main__‘: 15 test_socket_timeout()
2. AF_INET和SOCK_STREAM解释
1 # 地址簇 2 # socket.AF_INET IPv4(默认) 3 # socket.AF_INET6 IPv6 4 # socket.AF_UNIX 只能够用于单一的Unix系统进程间通信 5 6 # socket.SOCK_STREAM(数据流) 提供面向连接的稳定数据传输,即TCP/IP协议.多用于资料(如文件)传送。
3.gettimeout()和settimeout()解释
1 def gettimeout(self): # real signature unknown; restored from __doc__ 2 """ 3 gettimeout() -> timeout 4 5 Returns the timeout in seconds (float) associated with socket 6 operations. A timeout of None indicates that timeouts on socket 7 operations are disabled. 8 """ 9 return timeout 10 11 12 def settimeout(self, timeout): # real signature unknown; restored from __doc__ 13 """ 14 settimeout(timeout) 15 16 Set a timeout on socket operations. ‘timeout‘ can be a float, 17 giving in seconds, or None. Setting a timeout of None disables 18 the timeout feature and is equivalent to setblocking(1). 19 Setting a timeout of zero is the same as setblocking(0). 20 """ 21 pass 22 # 设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。 23 # 一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如 client 连接最多等待5s )
4.运行结果
1 Default socket timeout: None 2 Current socket timeout: 100.0
时间: 2024-10-18 13:52:31