当前位置: 首页>>代码示例>>Python>>正文


Python socket.SO_KEEPALIVE属性代码示例

本文整理汇总了Python中socket.SO_KEEPALIVE属性的典型用法代码示例。如果您正苦于以下问题:Python socket.SO_KEEPALIVE属性的具体用法?Python socket.SO_KEEPALIVE怎么用?Python socket.SO_KEEPALIVE使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在socket的用法示例。


在下文中一共展示了socket.SO_KEEPALIVE属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: start

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def start(self):
		family, socktype, proto, _, sockaddr = socket.getaddrinfo(self.host, self.port, self.family, self.type)[0]

		sock = socket.socket(family, socktype)
		sock.connect(sockaddr)

		if self.nodelay:
			sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

		if self.keepalive:
			sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

		if hasattr(socket, "TCP_KEEPIDLE") and hasattr(socket, "TCP_KEEPINTVL") and hasattr(socket, "TCP_KEEPCNT"):
			sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1 * 60)
			sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 30)
			sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
		elif hasattr(socket, "SIO_KEEPALIVE_VALS"):
			sock.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 1 * 60 * 1000, 5 * 60 * 1000))

		self.sock = sock
		self.recv_count = 0

		Ksecurity().reset_aes() 
开发者ID:turingsec,项目名称:marsnake,代码行数:25,代码来源:ksocket.py

示例2: _connect

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def _connect(self):
        self.logger.debug("Connecting to {} using {} {} on TCP port {} {} autoreconnect".format(self._host, 'IPv6' if self._ipver == socket.AF_INET6 else 'IPv4', self._hostip, self._port, ('with' if self._autoreconnect else 'without')))
        # Try to connect to remote host using ip (v4 or v6)
        try:
            self._socket = socket.socket(self._ipver, socket.SOCK_STREAM)
            self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            self._socket.settimeout(5)
            self._socket.connect(('{}'.format(self._hostip), int(self._port)))
            self._socket.settimeout(self._timeout)
            self._is_connected = True
            self.logger.info("Connected to {} on TCP port {}".format(self._host, self._port))
        # Connection error
        except Exception as err:
            self._is_connected = False
            self._connect_counter += 1
            self.logger.warning("TCP connection to {}:{} failed with error {}. Counter: {}/{}".format(self._host, self._port, err, self._connect_counter, self._connect_retries)) 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:18,代码来源:network.py

示例3: _connect

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def _connect(cls, host, port, family = socket.AF_INET, socktype = socket.SOCK_STREAM,
            proto = 0, timeout = 3, nodelay = False, keepalive = False):
        family, socktype, proto, _, sockaddr = socket.getaddrinfo(host, port, family, 
            socktype, proto)[0]
        s = socket.socket(family, socktype, proto)
        s.settimeout(timeout)
        s.connect(sockaddr)
        if nodelay:
            s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        if keepalive:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            # Linux specific: after 10 idle minutes, start sending keepalives every 5 minutes. 
            # Drop connection after 10 failed keepalives
            if hasattr(socket, "TCP_KEEPIDLE") and hasattr(socket, "TCP_KEEPINTVL") and hasattr(socket, "TCP_KEEPCNT"):
                s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10 * 60)
                s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5 * 60)
                s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 10)    
        return s 
开发者ID:krintoxi,项目名称:NoobSec-Toolkit,代码行数:20,代码来源:stream.py

示例4: test_connect_tcp_keepalive_options

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def test_connect_tcp_keepalive_options(event_loop):
    conn = Connection(
        loop=event_loop,
        socket_keepalive=True,
        socket_keepalive_options={
            socket.TCP_KEEPIDLE: 1,
            socket.TCP_KEEPINTVL: 1,
            socket.TCP_KEEPCNT: 3,
        },
    )
    await conn._connect()
    sock = conn._writer.transport.get_extra_info('socket')
    assert sock.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) == 1
    for k, v in (
        (socket.TCP_KEEPIDLE, 1),
        (socket.TCP_KEEPINTVL, 1),
        (socket.TCP_KEEPCNT, 3),
    ):
        assert sock.getsockopt(socket.SOL_TCP, k) == v
    conn.disconnect() 
开发者ID:NoneGG,项目名称:aredis,代码行数:22,代码来源:test_connection.py

示例5: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def __init__(self, nodes, **kwargs):
        if kwargs.get('tcp_keepalive', True):
            socket_options = HTTPConnection.default_socket_options + \
                             [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), ]
        else:
            socket_options = HTTPConnection.default_socket_options

        self.http = urllib3.poolmanager.PoolManager(
            num_pools=kwargs.get('num_pools', 10),
            maxsize=kwargs.get('maxsize', 64),
            timeout=kwargs.get('timeout', 30),
            socket_options=socket_options,
            block=False,
            retries=Retry(total=False),
            headers={
                'Content-Type': 'application/json',
                'accept-encoding': 'gzip'},
            cert_reqs='CERT_REQUIRED',
            ca_certs=certifi.where())

        self.nodes = cycle(nodes)
        self.url = ''
        self.request = None
        self.next_node() 
开发者ID:steemit,项目名称:hivemind,代码行数:26,代码来源:http_client.py

示例6: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def __init__(self, **kwargs):
        socket_options = kwargs.pop('socket_options',
                                    SocketOptionsAdapter.default_options)
        idle = kwargs.pop('idle', 60)
        interval = kwargs.pop('interval', 20)
        count = kwargs.pop('count', 5)
        socket_options = socket_options + [
            (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
            (socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval),
            (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, count),
        ]

        # NOTE(Ian): Apparently OSX does not have this constant defined, so we
        # set it conditionally.
        if getattr(socket, 'TCP_KEEPIDLE', None) is not None:
            socket_options += [(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, idle)]

        super(TCPKeepAliveAdapter, self).__init__(
            socket_options=socket_options, **kwargs
        ) 
开发者ID:kylebebak,项目名称:Requester,代码行数:22,代码来源:socket_options.py

示例7: connect

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def connect(self, address, port, timeout = 0):
		self.close()
		af = socket.AF_INET
		if ':' in address:
			if not 'AF_INET6' in socket.__dict__:
				return -1
			if not socket.has_ipv6:
				return -2
			af = socket.AF_INET6
			self.ipv6 = True
		self.sock = socket.socket(af, socket.SOCK_STREAM)
		to = self.sock.gettimeout()
		self.sock.setblocking(0)
		self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
		self.state = NET_STATE_CONNECTING
		try:
			hr = self.sock.connect_ex((address, port))
		except socket.error, e:
			pass 
开发者ID:skywind3000,项目名称:collection,代码行数:21,代码来源:asyncredis.py

示例8: connect

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def connect(self):
        # create socket, connect to server, login and make a file object associated with the socket
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

        if self.aprs_filter:
            port = self.settings.APRS_SERVER_PORT_CLIENT_DEFINED_FILTERS
        else:
            port = self.settings.APRS_SERVER_PORT_FULL_FEED

        self.sock.connect((self.settings.APRS_SERVER_HOST, port))
        self.logger.debug('Server port {}'.format(port))

        login = create_aprs_login(self.aprs_user, -1, self.settings.APRS_APP_NAME, self.settings.APRS_APP_VER, self.aprs_filter)
        self.sock.send(login.encode())
        self.sock_file = self.sock.makefile('rw')

        self._kill = False 
开发者ID:glidernet,项目名称:python-ogn-client,代码行数:20,代码来源:client.py

示例9: test_socket_options_for_simple_server

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def test_socket_options_for_simple_server(self):
        # test normal socket options has set properly
        self.flags(tcp_keepidle=500, group='wsgi')
        server = masakari.wsgi.Server("test_socket_options", None,
                                  host="127.0.0.1", port=0)
        server.start()
        sock = server._socket
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_REUSEADDR))
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_KEEPALIVE))
        if hasattr(socket, 'TCP_KEEPIDLE'):
            self.assertEqual(CONF.wsgi.tcp_keepidle,
                             sock.getsockopt(socket.IPPROTO_TCP,
                                             socket.TCP_KEEPIDLE))
        server.stop()
        server.wait() 
开发者ID:openstack,项目名称:masakari,代码行数:19,代码来源:test_wsgi.py

示例10: get_simple_socket

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def get_simple_socket(self):
        try:
            l = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM)
        except socket.gaierror:
            log.error("cannot resolve hostname")
            return
        for res in l:
            try:
                s = socket.socket(res[0], socket.SOCK_STREAM)
                s.connect(res[4])
                s.settimeout(2)
                s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                return s
            except BaseException as e:
                log.exception('Failed to connect to %s', res)
                continue 
开发者ID:UlordChain,项目名称:Uwallet,代码行数:18,代码来源:interface.py

示例11: test_socket_options_for_simple_server

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def test_socket_options_for_simple_server(self):
        # test normal socket options has set properly
        self.config(tcp_keepidle=500)
        server = wsgi.Server(self.conf, "test_socket_options", None,
                             host="127.0.0.1", port=0)
        server.start()
        sock = server.socket
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_REUSEADDR))
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_KEEPALIVE))
        if hasattr(socket, 'TCP_KEEPIDLE'):
            self.assertEqual(self.conf.tcp_keepidle,
                             sock.getsockopt(socket.IPPROTO_TCP,
                                             socket.TCP_KEEPIDLE))
        self.assertFalse(server._server.dead)
        server.stop()
        server.wait()
        self.assertTrue(server._server.dead) 
开发者ID:openstack,项目名称:oslo.service,代码行数:21,代码来源:test_wsgi.py

示例12: test_socket_options_for_ssl_server

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def test_socket_options_for_ssl_server(self):
        # test normal socket options has set properly
        self.config(tcp_keepidle=500)
        server = wsgi.Server(self.conf, "test_socket_options", None,
                             host="127.0.0.1", port=0, use_ssl=True)
        server.start()
        sock = server.socket
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_REUSEADDR))
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_KEEPALIVE))
        if hasattr(socket, 'TCP_KEEPIDLE'):
            self.assertEqual(CONF.tcp_keepidle,
                             sock.getsockopt(socket.IPPROTO_TCP,
                                             socket.TCP_KEEPIDLE))
        server.stop()
        server.wait() 
开发者ID:openstack,项目名称:oslo.service,代码行数:19,代码来源:test_wsgi.py

示例13: start

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def start(self, key=None, backlog=128):
        """Run a WSGI server with the given application."""

        if self.socket is None:
            self.listen(key=key, backlog=backlog)

        dup_socket = self.socket.dup()
        if key:
            self.socket_info[key] = self.socket.getsockname()

        # Optionally enable keepalive on the wsgi socket.
        if self.keepalive:
            dup_socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

            if self.keepidle is not None:
                dup_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE,
                                      self.keepidle)

        self.greenthread = self.pool.spawn(self._run,
                                           self.application,
                                           dup_socket) 
开发者ID:openstack,项目名称:oslo.service,代码行数:23,代码来源:eventlet_service.py

示例14: get_socket

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def get_socket(address):
        """
        根据配置信息建立tcp连接
        Args:
            address: host:name字符串

        Returns:
            建立成功返回socket对象, 失败返回False
        """
        (ip, port) = address.split(':')
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)  # 在客户端开启心跳维护
        try:
            s.connect((ip, int(port)))
        except socket.error:
            return False
        else:
            return s 
开发者ID:iyaozhen,项目名称:filebeat.py,代码行数:20,代码来源:filebeat.py

示例15: set_keepalive

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_KEEPALIVE [as 别名]
def set_keepalive(sock: socket.socket) -> None:
    """sets the SO_KEEPALIVE option on the socket, if possible."""
    with contextlib.suppress(Exception):
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) 
开发者ID:irmen,项目名称:Pyro5,代码行数:6,代码来源:socketutil.py


注:本文中的socket.SO_KEEPALIVE属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。