本文整理汇总了Python中socket.SO_RCVTIMEO属性的典型用法代码示例。如果您正苦于以下问题:Python socket.SO_RCVTIMEO属性的具体用法?Python socket.SO_RCVTIMEO怎么用?Python socket.SO_RCVTIMEO使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类socket
的用法示例。
在下文中一共展示了socket.SO_RCVTIMEO属性的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_socket_io_timeouts
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_RCVTIMEO [as 别名]
def set_socket_io_timeouts(transport, seconds, useconds=0):
"""
Set timeout for transport sockets.
Useful with highly concurrent workloads.
Returns False if it failed to set the timeouts.
"""
seconds = (seconds).to_bytes(8, 'little')
useconds = (useconds).to_bytes(8, 'little')
sock = transport.get_extra_info('socket')
try:
sock.setsockopt(
socket.SOL_SOCKET,
socket.SO_RCVTIMEO,
seconds + useconds,
)
sock.setsockopt(
socket.SOL_SOCKET,
socket.SO_SNDTIMEO,
seconds + useconds,
)
return True
except OSError:
return False
示例2: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_RCVTIMEO [as 别名]
def __init__(self, server_ip, server_port, rxque_max=XCONF.SocketConf.TCP_RX_QUE_MAX, heartbeat=False,
buffer_size=XCONF.SocketConf.TCP_CONTROL_BUF_SIZE):
super(SocketPort, self).__init__(rxque_max)
if server_port == XCONF.SocketConf.TCP_CONTROL_PORT:
self.port_type = 'main-socket'
# self.com.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, 5)
else:
self.port_type = 'report-socket'
try:
socket.setdefaulttimeout(1)
self.com = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.com.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.com.setblocking(True)
self.com.settimeout(1)
self.com.connect((server_ip, server_port))
logger.info('{} connect {} success'.format(self.port_type, server_ip))
# logger.info('{} connect {}:{} success'.format(self.port_type, server_ip, server_port))
self._connected = True
self.buffer_size = buffer_size
# time.sleep(1)
self.rx_parse = -1
self.com_read = self.com.recv
self.com_write = self.com.send
self.write_lock = threading.Lock()
self.start()
if heartbeat:
self.heartbeat_thread = HeartBeatThread(self)
self.heartbeat_thread.start()
except Exception as e:
logger.info('{} connect {} failed, {}'.format(self.port_type, server_ip, e))
# logger.error('{} connect {}:{} failed, {}'.format(self.port_type, server_ip, server_port, e))
self._connected = False
示例3: open
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_RCVTIMEO [as 别名]
def open(self):
"""
Opens connection to the target. Make sure to call close!
Returns:
None
"""
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, _seconds_to_sockopt_format(self._send_timeout))
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, _seconds_to_sockopt_format(self._recv_timeout))
示例4: new_accept
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_RCVTIMEO [as 别名]
def new_accept(orgin_method, self, *args, **kwds):
while True:
return_value = orgin_method(*args, **kwds)
self_socket = return_value[0]
client_ip, client_port = return_value[1][:2]
server_addrs = self._server_addrs
client_list = self._all_client_list.get(server_addrs, {})
if len(client_list) < self._limit_clients_num or client_ip in client_list:
self_socket._server_addrs = self._server_addrs
self_socket.close = self_socket.new_close
logging.debug("[socket] add client %s:%d" %(client_ip, client_port))
if client_list.get(client_ip, None) == None:
client_list.update({client_ip : {"client_num":0, "last_up_time":0}})
client_list[client_ip]["client_num"] += 1
self._all_client_list[server_addrs].update(client_list)
if set_close_timeout:
# set recv_timeout and send_timeout , struct.pack("II", some_num_secs, some_num_microsecs)
self_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.pack("LL", recv_timeout, 0))
self_socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, struct.pack("LL", send_timeout, 0))
return return_value
else:
for k,v in self._all_client_list[server_addrs].copy().items():
last_up_time = v["last_up_time"]
if time.time() - last_up_time > recvfrom_timeout and v["client_num"] < 1:
if set_close_timeout:
self_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.pack("LL", recv_timeout, 0))
self_socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, struct.pack("LL", send_timeout, 0))
logging.info("[socket] remove the client %s" % (k))
del client_list[k]
if client_list.get(client_ip, None) == None:
client_list.update({client_ip : {"client_num":0, "last_up_time":0}})
client_list[client_ip]["client_num"] += 1
self._all_client_list[server_addrs].update(client_list)
self_socket._server_addrs = self._server_addrs
self_socket.close = self_socket.new_close
return return_value
if time.time() - self.last_log_time[0] > 10:
logging.error("[socket] the server_addrs %s client more than %d" % (server_addrs, self._limit_clients_num))
self.last_log_time[0] = time.time()
self_socket.close()
# 处理Udp连接
示例5: open
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_RCVTIMEO [as 别名]
def open(self):
"""
Opens connection to the target. Make sure to call close!
Returns:
None
"""
# Create socket
if self.proto == "tcp" or self.proto == "ssl":
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
elif self.proto == "udp":
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if self.bind:
self._sock.bind(('0.0.0.0', self.bind))
if self._udp_broadcast:
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)
elif self.proto == "raw-l2":
self._sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
elif self.proto == "raw-l3":
self._sock = socket.socket(socket.AF_PACKET, socket.SOCK_DGRAM)
else:
raise exception.FuzzowskiRuntimeError("INVALID PROTOCOL SPECIFIED: %s" % self.proto)
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, _seconds_to_second_microsecond_struct(self._send_timeout))
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, _seconds_to_second_microsecond_struct(self._recv_timeout))
# Connect is needed only for TCP protocols
if self.proto == "tcp" or self.proto == "ssl":
try:
self._sock.settimeout(self._recv_timeout)
self._sock.connect((self.host, self.port))
except (socket.timeout, TimeoutError) as e:
raise exception.FuzzowskiTargetConnectionFailedError('ETIMEDOUT')
except OSError as e: # socket.error
if e.errno == errno.ECONNREFUSED:
# raise exception.FuzzowskiTargetConnectionFailedError(e.message)
raise exception.FuzzowskiTargetConnectionFailedError('ECONNREFUSED')
elif e.errno == errno.EALREADY:
raise exception.FuzzowskiTargetConnectionFailedError('EALREADY')
elif e.errno == errno.EINPROGRESS:
raise exception.FuzzowskiTargetConnectionFailedError('EINPROGRESS')
else: # ??
raise exception.FuzzowskiTargetConnectionFailedError(errno.errorcode.get(e.errno))
# if SSL is requested, then enable it.
if self.proto == "ssl":
ssl_sock = ssl.wrap_socket(self._sock)
# TODO: Python3 change, maybe should use a context instead of deprecated ssl.wrap_socket?
self._sock = ssl_sock
# self._sock = httplib.FakeSocket(self._sock, ssl_sock)
示例6: recv
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_RCVTIMEO [as 别名]
def recv(self, max_bytes):
"""
Receive up to max_bytes data from the target.
Args:
max_bytes (int): Maximum number of bytes to receive.
Returns:
Received data.
"""
try:
if self.proto in ['tcp', 'ssl']:
data = self._sock.recv(max_bytes)
elif self.proto == 'udp':
# Not necessary to bind to a port to use this, right?
# if self.bind:
data, _ = self._sock.recvfrom(max_bytes)
# else:
# raise exception.FuzzowskiRuntimeError(
# "SocketConnection.recv() for UDP requires a bind address/port."
# " Current value: {}".format(self.bind))
elif self.proto in ['raw-l2', 'raw-l3']:
# receive on raw is not supported. Since there is no specific protocol for raw, we would just have to
# dump everything off the interface anyway, which is probably not what the user wants.
data = b''
else:
raise exception.FuzzowskiRuntimeError("INVALID PROTOCOL SPECIFIED: %s" % self.proto)
except socket.timeout:
data = b''
# raise exception.FuzzowskiTargetRecvTimeout()
except socket.error as e:
if e.errno == errno.ECONNABORTED:
# raise(exception.FuzzowskiTargetConnectionAborted(socket_errno=e.errno, socket_errmsg=e.strerror), None, sys.exc_info()[2])
raise exception.FuzzowskiTargetConnectionAborted(socket_errno=e.errno, socket_errmsg=e.strerror) # .with_traceback(sys.exc_info()[2])
elif (e.errno == errno.ECONNRESET) or \
(e.errno == errno.ENETRESET) or \
(e.errno == errno.ETIMEDOUT):
# raise(exception.FuzzowskiTargetConnectionReset, None, sys.exc_info()[2])
raise exception.FuzzowskiTargetConnectionReset # .with_traceback(sys.exc_info()[2])
elif e.errno == errno.EWOULDBLOCK or e.errno == errno.EAGAIN: # timeout condition if using SO_RCVTIMEO or SO_SNDTIMEO
# raise exception.FuzzowskiTargetRecvTimeout()
data = b''
else:
raise
return data