发布网友 发布时间:2022-04-22 03:46
共2个回答
热心网友 时间:2022-04-18 06:34
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
热心网友 时间:2022-04-18 07:52
import socket
def shuncom_device_list(gw_ip):
global winds_ip
try:
winds_host_name = socket.gethostname()
winds_ip = socket.gethostbyname(winds_host_name) # 获取当前主机ip
ip_port = (gw_ip,8888)#网关的网段
udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_client.settimeout(10) #获取套接字默认超时时间10秒
udp_client.bind((winds_ip,9999)) #电脑ip和端口
send_data = '{"code":1,"key":"shuncom_device"}'
udp_client.sendto(bytes(send_data,encoding="utf-8"),ip_port)
gw_device_list = (udp_client.recv(1024)).decode('utf-8')
print(gw_device_list)
udp_client.close()
return gw_device_list
except:
print('连接%s 超时'%winds_ip)
shuncom_device_list('192.168.6.255')