Python socket.TCP_NODELAY() Examples

The following are 60 code examples for showing how to use socket.TCP_NODELAY(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

You may also check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: neverendshadowsocks   Author: ntfreedom   File: tcprelay.py    License: Apache License 2.0 6 votes vote down vote up
def _create_remote_socket(self, ip, port):
        addrs = socket.getaddrinfo(ip, port, 0, socket.SOCK_STREAM,
                                   socket.SOL_TCP)
        if len(addrs) == 0:
            raise Exception("getaddrinfo failed for %s:%d" % (ip, port))
        af, socktype, proto, canonname, sa = addrs[0]
        if self._forbidden_iplist:
            if common.to_str(sa[0]) in self._forbidden_iplist:
                raise Exception('IP %s is in forbidden list, reject' %
                                common.to_str(sa[0]))
        remote_sock = socket.socket(af, socktype, proto)
        self._remote_sock = remote_sock
        self._fd_to_handlers[remote_sock.fileno()] = self
        remote_sock.setblocking(False)
        remote_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
        return remote_sock 
Example 2
Project: SalesforceXyTools   Author: exiahuang   File: wsgiserver3.py    License: Apache License 2.0 6 votes vote down vote up
def bind(self, family, type, proto=0):
        """Create (or recreate) the actual socket object."""
        self.socket = socket.socket(family, type, proto)
        prevent_socket_inheritance(self.socket)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if self.nodelay and not isinstance(self.bind_addr, str):
            self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

        if self.ssl_adapter is not None:
            self.socket = self.ssl_adapter.bind(self.socket)

        # If listening on the IPV6 any address ('::' = IN6ADDR_ANY),
        # activate dual-stack. See https://bitbucket.org/cherrypy/cherrypy/issue/871.
        if (hasattr(socket, 'AF_INET6') and family == socket.AF_INET6
            and self.bind_addr[0] in ('::', '::0', '::0.0.0.0')):
            try:
                self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
            except (AttributeError, socket.error):
                # Apparently, the socket option is not available in
                # this machine's TCP stack
                pass

        self.socket.bind(self.bind_addr) 
Example 3
Project: SalesforceXyTools   Author: exiahuang   File: wsgiserver2.py    License: Apache License 2.0 6 votes vote down vote up
def bind(self, family, type, proto=0):
        """Create (or recreate) the actual socket object."""
        self.socket = socket.socket(family, type, proto)
        prevent_socket_inheritance(self.socket)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if self.nodelay and not isinstance(self.bind_addr, str):
            self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

        if self.ssl_adapter is not None:
            self.socket = self.ssl_adapter.bind(self.socket)

        # If listening on the IPV6 any address ('::' = IN6ADDR_ANY),
        # activate dual-stack. See https://bitbucket.org/cherrypy/cherrypy/issue/871.
        if (hasattr(socket, 'AF_INET6') and family == socket.AF_INET6
            and self.bind_addr[0] in ('::', '::0', '::0.0.0.0')):
            try:
                self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
            except (AttributeError, socket.error):
                # Apparently, the socket option is not available in
                # this machine's TCP stack
                pass

        self.socket.bind(self.bind_addr) 
Example 4
Project: selenium-wire   Author: wkeeling   File: proxy2.py    License: MIT License 6 votes vote down vote up
def _socks_connection(host, port, timeout, socks_config):
    """Create a SOCKS connection based on the supplied configuration."""
    try:
        socks_type = dict(
            socks4=socks.PROXY_TYPE_SOCKS4,
            socks5=socks.PROXY_TYPE_SOCKS5,
            socks5h=socks.PROXY_TYPE_SOCKS5
        )[socks_config.scheme]
    except KeyError:
        raise TypeError('Invalid SOCKS scheme: {}'.format(socks_config.scheme))

    socks_host, socks_port = socks_config.hostport.split(':')

    return socks.create_connection(
        (host, port),
        timeout,
        None,
        socks_type,
        socks_host,
        int(socks_port),
        socks_config.scheme == 'socks5h',
        socks_config.username,
        socks_config.password,
        ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),)
    ) 
Example 5
Project: selenium-wire   Author: wkeeling   File: test_proxy2.py    License: MIT License 6 votes vote down vote up
def test_connect_uses_socks5_proxy(self, mock_socks):
        conf = namedtuple('ProxyConf', 'scheme username password hostport')
        self.config = {
            'http': conf(*_parse_proxy('socks5://socks_user:socks_pass@socks_host:3128')),
            'no_proxy': 'localhost,127.0.0.1,dev_server:8080'
        }
        mock_socks.PROXY_TYPE_SOCKS5 = socks.PROXY_TYPE_SOCKS5

        conn = ProxyAwareHTTPConnection(self.config, 'example.com')
        conn.connect()

        mock_socks.create_connection.assert_called_once_with(
            ('example.com', 80),
            socket._GLOBAL_DEFAULT_TIMEOUT,
            None,
            socks.PROXY_TYPE_SOCKS5,
            'socks_host',
            3128,
            False,
            'socks_user',
            'socks_pass',
            ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),)
        ) 
Example 6
Project: selenium-wire   Author: wkeeling   File: test_proxy2.py    License: MIT License 6 votes vote down vote up
def test_connect_uses_remote_dns(self, mock_socks):
        conf = namedtuple('ProxyConf', 'scheme username password hostport')
        self.config = {
            'http': conf(*_parse_proxy('socks5h://socks_user:socks_pass@socks_host:3128')),
            'no_proxy': 'localhost,127.0.0.1,dev_server:8080'
        }
        mock_socks.PROXY_TYPE_SOCKS5 = socks.PROXY_TYPE_SOCKS5

        conn = ProxyAwareHTTPConnection(self.config, 'example.com')
        conn.connect()

        mock_socks.create_connection.assert_called_once_with(
            ('example.com', 80),
            socket._GLOBAL_DEFAULT_TIMEOUT,
            None,
            socks.PROXY_TYPE_SOCKS5,
            'socks_host',
            3128,
            True,
            'socks_user',
            'socks_pass',
            ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),)
        ) 
Example 7
Project: selenium-wire   Author: wkeeling   File: test_proxy2.py    License: MIT License 6 votes vote down vote up
def test_connect_uses_socks4_proxy(self, mock_socks):
        conf = namedtuple('ProxyConf', 'scheme username password hostport')
        self.config = {
            'http': conf(*_parse_proxy('socks4://socks_user:socks_pass@socks_host:3128')),
            'no_proxy': 'localhost,127.0.0.1,dev_server:8080'
        }
        mock_socks.PROXY_TYPE_SOCKS4 = socks.PROXY_TYPE_SOCKS4

        conn = ProxyAwareHTTPConnection(self.config, 'example.com')
        conn.connect()

        mock_socks.create_connection.assert_called_once_with(
            ('example.com', 80),
            socket._GLOBAL_DEFAULT_TIMEOUT,
            None,
            socks.PROXY_TYPE_SOCKS4,
            'socks_host',
            3128,
            False,
            'socks_user',
            'socks_pass',
            ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),)
        ) 
Example 8
Project: selenium-wire   Author: wkeeling   File: test_proxy2.py    License: MIT License 6 votes vote down vote up
def test_connect_uses_socks5_proxy(self, mock_socks):
        conf = namedtuple('ProxyConf', 'scheme username password hostport')
        self.config = {
            'https': conf(*_parse_proxy('socks5://socks_user:socks_pass@socks_host:3128')),
            'no_proxy': 'localhost,127.0.0.1,dev_server:8080'
        }
        mock_socks.PROXY_TYPE_SOCKS5 = socks.PROXY_TYPE_SOCKS5

        conn = ProxyAwareHTTPSConnection(self.config, 'example.com', context=Mock())
        conn.connect()

        mock_socks.create_connection.assert_called_once_with(
            ('example.com', 443),
            socket._GLOBAL_DEFAULT_TIMEOUT,
            None,
            socks.PROXY_TYPE_SOCKS5,
            'socks_host',
            3128,
            False,
            'socks_user',
            'socks_pass',
            ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),)
        ) 
Example 9
Project: selenium-wire   Author: wkeeling   File: test_proxy2.py    License: MIT License 6 votes vote down vote up
def test_connect_uses_socks4_proxy(self, mock_socks):
        conf = namedtuple('ProxyConf', 'scheme username password hostport')
        self.config = {
            'https': conf(*_parse_proxy('socks4://socks_user:socks_pass@socks_host:3128')),
            'no_proxy': 'localhost,127.0.0.1,dev_server:8080'
        }
        mock_socks.PROXY_TYPE_SOCKS4 = socks.PROXY_TYPE_SOCKS4

        conn = ProxyAwareHTTPSConnection(self.config, 'example.com', context=Mock())
        conn.connect()

        mock_socks.create_connection.assert_called_once_with(
            ('example.com', 443),
            socket._GLOBAL_DEFAULT_TIMEOUT,
            None,
            socks.PROXY_TYPE_SOCKS4,
            'socks_host',
            3128,
            False,
            'socks_user',
            'socks_pass',
            ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),)
        ) 
Example 10
Project: nightmare   Author: joxeankoret   File: __init__.py    License: GNU General Public License v2.0 6 votes vote down vote up
def bind(self, family, type, proto=0):
        """Create (or recreate) the actual socket object."""
        self.socket = socket.socket(family, type, proto)
        prevent_socket_inheritance(self.socket)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if self.nodelay and not isinstance(self.bind_addr, str):
            self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        
        if self.ssl_adapter is not None:
            self.socket = self.ssl_adapter.bind(self.socket)
        
        # If listening on the IPV6 any address ('::' = IN6ADDR_ANY),
        # activate dual-stack. See http://www.cherrypy.org/ticket/871.
        if (hasattr(socket, 'AF_INET6') and family == socket.AF_INET6
            and self.bind_addr[0] in ('::', '::0', '::0.0.0.0')):
            try:
                self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
            except (AttributeError, socket.error):
                # Apparently, the socket option is not available in
                # this machine's TCP stack
                pass
        
        self.socket.bind(self.bind_addr) 
Example 11
Project: oss-ftp   Author: aliyun   File: test_functional.py    License: MIT License 6 votes vote down vote up
def tearDown(self):
        os.remove(TESTFN)
        # set back options to their original value
        self.server.server.max_cons = 0
        self.server.server.max_cons_per_ip = 0
        self.server.handler.banner = "pyftpdlib ready."
        self.server.handler.max_login_attempts = 3
        self.server.handler.auth_failed_timeout = 5
        self.server.handler.masquerade_address = None
        self.server.handler.masquerade_address_map = {}
        self.server.handler.permit_privileged_ports = False
        self.server.handler.passive_ports = None
        self.server.handler.use_gmt_times = True
        self.server.handler.tcp_no_delay = hasattr(socket, 'TCP_NODELAY')
        self.server.stop()
        self.client.close() 
Example 12
Project: oss-ftp   Author: aliyun   File: test_functional.py    License: MIT License 6 votes vote down vote up
def test_tcp_no_delay(self):
        def get_handler_socket():
            # return the server's handler socket object
            ioloop = IOLoop.instance()
            for fd in ioloop.socket_map:
                instance = ioloop.socket_map[fd]
                if isinstance(instance, FTPHandler):
                    break
            return instance.socket

        s = get_handler_socket()
        self.assertTrue(s.getsockopt(socket.SOL_TCP, socket.TCP_NODELAY))
        self.client.quit()
        self.server.handler.tcp_no_delay = False
        self.client.connect(self.server.host, self.server.port)
        self.client.sendcmd('noop')
        s = get_handler_socket()
        self.assertFalse(s.getsockopt(socket.SOL_TCP, socket.TCP_NODELAY)) 
Example 13
Project: oss-ftp   Author: aliyun   File: test_functional.py    License: MIT License 6 votes vote down vote up
def tearDown(self):
        os.remove(TESTFN)
        # set back options to their original value
        self.server.server.max_cons = 0
        self.server.server.max_cons_per_ip = 0
        self.server.handler.banner = "pyftpdlib ready."
        self.server.handler.max_login_attempts = 3
        self.server.handler.auth_failed_timeout = 5
        self.server.handler.masquerade_address = None
        self.server.handler.masquerade_address_map = {}
        self.server.handler.permit_privileged_ports = False
        self.server.handler.passive_ports = None
        self.server.handler.use_gmt_times = True
        self.server.handler.tcp_no_delay = hasattr(socket, 'TCP_NODELAY')
        self.server.stop()
        self.client.close() 
Example 14
Project: oss-ftp   Author: aliyun   File: test_functional.py    License: MIT License 6 votes vote down vote up
def test_tcp_no_delay(self):
        def get_handler_socket():
            # return the server's handler socket object
            ioloop = IOLoop.instance()
            for fd in ioloop.socket_map:
                instance = ioloop.socket_map[fd]
                if isinstance(instance, FTPHandler):
                    break
            return instance.socket

        s = get_handler_socket()
        self.assertTrue(s.getsockopt(socket.SOL_TCP, socket.TCP_NODELAY))
        self.client.quit()
        self.server.handler.tcp_no_delay = False
        self.client.connect(self.server.host, self.server.port)
        self.client.sendcmd('noop')
        s = get_handler_socket()
        self.assertFalse(s.getsockopt(socket.SOL_TCP, socket.TCP_NODELAY)) 
Example 15
Project: Safejumper-for-Desktop   Author: proxysh   File: posixbase.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, reactor):
        """Initialize.
        """
        self.reactor = reactor
        # Following select_trigger (from asyncore)'s example;
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        server.bind(('127.0.0.1', 0))
        server.listen(1)
        client.connect(server.getsockname())
        reader, clientaddr = server.accept()
        client.setblocking(0)
        reader.setblocking(0)
        self.r = reader
        self.w = client
        self.fileno = self.r.fileno 
Example 16
Project: ddt4all   Author: cedricp   File: elm.py    License: GNU General Public License v3.0 6 votes vote down vote up
def init_wifi(self, reinit=False):
        '''
        Needed for wifi adapters with short connection timeout
        '''
        if self.portType != 1:
            return

        import socket

        if reinit:
            self.hdr.close()
        self.hdr = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.hdr.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        try:
            self.hdr.connect((self.ipaddr, self.tcpprt))
            self.hdr.setblocking(True)
            self.connectionStatus = True
        except:
            options.elm_failed = True 
Example 17
Project: pysphere   Author: rnbguy   File: misphere.py    License: MIT License 5 votes vote down vote up
def init(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        self.socket.connect((self.ms_ip, self.ms_tcp_port))
        self.socket_1 = socket.socket()
        self.recv_handle_live = True
        self.recv_thread = threading.Thread(target=self.recv_handler)
        self.recv_thread.daemon = True
        self.session = Session()
        self.session.conf = {}
        self.session.locks = {}
        self.last_send = 0 
Example 18
Project: verge3d-blender-addon   Author: Soft8Soft   File: socketserver.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setup(self):
        self.connection = self.request
        if self.timeout is not None:
            self.connection.settimeout(self.timeout)
        if self.disable_nagle_algorithm:
            self.connection.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, True)
        self.rfile = self.connection.makefile('rb', self.rbufsize)
        self.wfile = self.connection.makefile('wb', self.wbufsize) 
Example 19
Project: misp42splunk   Author: remg427   File: socketserver.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def setup(self):
        self.connection = self.request
        if self.timeout is not None:
            self.connection.settimeout(self.timeout)
        if self.disable_nagle_algorithm:
            self.connection.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, True)
        self.rfile = self.connection.makefile('rb', self.rbufsize)
        self.wfile = self.connection.makefile('wb', self.wbufsize) 
Example 20
Project: misp42splunk   Author: remg427   File: socketserver.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def setup(self):
        self.connection = self.request
        if self.timeout is not None:
            self.connection.settimeout(self.timeout)
        if self.disable_nagle_algorithm:
            self.connection.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, True)
        self.rfile = self.connection.makefile('rb', self.rbufsize)
        self.wfile = self.connection.makefile('wb', self.wbufsize) 
Example 21
Project: tornado-zh   Author: tao12345666333   File: iostream.py    License: MIT License 5 votes vote down vote up
def set_nodelay(self, value):
        if (self.socket is not None and
                self.socket.family in (socket.AF_INET, socket.AF_INET6)):
            try:
                self.socket.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, 1 if value else 0)
            except socket.error as e:
                # Sometimes setsockopt will fail if the socket is closed
                # at the wrong time.  This can happen with HTTPServer
                # resetting the value to false between requests.
                if e.errno != errno.EINVAL and not self._is_connreset(e):
                    raise 
Example 22
Project: tornado-zh   Author: tao12345666333   File: iostream.py    License: MIT License 5 votes vote down vote up
def set_nodelay(self, value):
        if (self.socket is not None and
                self.socket.family in (socket.AF_INET, socket.AF_INET6)):
            try:
                self.socket.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, 1 if value else 0)
            except socket.error as e:
                # Sometimes setsockopt will fail if the socket is closed
                # at the wrong time.  This can happen with HTTPServer
                # resetting the value to false between requests.
                if e.errno != errno.EINVAL and not self._is_connreset(e):
                    raise 
Example 23
Project: bilibiliupload   Author: ForgQi   File: rangefetch_server.py    License: MIT License 5 votes vote down vote up
def server_bind(self):
        sock = self.socket
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True)
        self.RequestHandlerClass.bufsize = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        SocketServer.TCPServer.server_bind(self) 
Example 24
Project: Pyro5   Author: irmen   File: socketutil.py    License: MIT License 5 votes vote down vote up
def set_nodelay(sock: socket.socket) -> None:
    """sets the TCP_NODELAY option on the socket (to disable Nagle's algorithm), if possible."""
    with contextlib.suppress(Exception):
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 
Example 25
Project: jbox   Author: jpush   File: sock.py    License: MIT License 5 votes vote down vote up
def set_options(self, sock, bound=False):
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        return super(TCPSocket, self).set_options(sock, bound=bound) 
Example 26
Project: neverendshadowsocks   Author: ntfreedom   File: tcprelay.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, server, fd_to_handlers, loop, local_sock, config,
                 dns_resolver, is_local):
        self._server = server
        self._fd_to_handlers = fd_to_handlers
        self._loop = loop
        self._local_sock = local_sock
        self._remote_sock = None
        self._config = config
        self._dns_resolver = dns_resolver

        # TCP Relay works as either sslocal or ssserver
        # if is_local, this is sslocal
        self._is_local = is_local
        self._stage = STAGE_INIT
        self._encryptor = encrypt.Encryptor(config['password'],
                                            config['method'])
        self._fastopen_connected = False
        self._data_to_write_to_local = []
        self._data_to_write_to_remote = []
        self._upstream_status = WAIT_STATUS_READING
        self._downstream_status = WAIT_STATUS_INIT
        self._client_address = local_sock.getpeername()[:2]
        self._remote_address = None
        if 'forbidden_ip' in config:
            self._forbidden_iplist = config['forbidden_ip']
        else:
            self._forbidden_iplist = None
        if is_local:
            self._chosen_server = self._get_a_server()
        fd_to_handlers[local_sock.fileno()] = self
        local_sock.setblocking(False)
        local_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
        loop.add(local_sock, eventloop.POLL_IN | eventloop.POLL_ERR,
                 self._server)
        self.last_activity = 0
        self._update_activity() 
Example 27
Project: NVDARemote   Author: NVDARemote   File: server.py    License: GNU General Public License v2.0 5 votes vote down vote up
def accept_new_connection(self, sock):
		try:
			client_sock, addr = sock.accept()
		except (ssl.SSLError, socket.error, OSError):
			return
		client_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
		client = Client(server=self, socket=client_sock)
		self.add_client(client) 
Example 28
Project: NVDARemote   Author: NVDARemote   File: transport.py    License: GNU General Public License v2.0 5 votes vote down vote up
def create_outbound_socket(self, address):
		address = socket.getaddrinfo(*address)[0]
		server_sock = socket.socket(*address[:3])
		if self.timeout:
			server_sock.settimeout(self.timeout)
		server_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
		server_sock.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 60000, 2000))
		server_sock = ssl.wrap_socket(server_sock)
		return server_sock 
Example 29
Project: aliyun-mns   Author: gikoluo   File: mns_http.py    License: MIT License 5 votes vote down vote up
def send_request(self, req_inter):
        try:
            if self.logger:
                self.logger.debug("SendRequest %s" % req_inter)
            self.conn.request(req_inter.method, req_inter.uri, req_inter.data, req_inter.header)
            self.conn.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            try:
                http_resp = self.conn.getresponse()
            except BadStatusLine:
                #open another connection when keep-alive timeout
                #httplib will not handle keep-alive timeout, so we must handle it ourself
                self.conn.close()
                self.conn.request(req_inter.method, req_inter.uri, req_inter.data, req_inter.header)
                self.conn.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
                http_resp = self.conn.getresponse()
            try:
                headers = http_resp.headers
            except:
                headers = dict(http_resp.getheaders())

            resp_inter = ResponseInternal(status = http_resp.status, header = headers, data = http_resp.read())
            self.request_size = self.conn.request_length
            self.response_size = len(resp_inter.data)
            if not self.is_keep_alive():
                self.conn.close()
            if self.logger:
                self.logger.debug("GetResponse %s" % resp_inter)
            return resp_inter
        except Exception as e:
            self.conn.close()
            raise MNSClientNetworkException("NetWorkException", str(e), req_inter.get_req_id()) #raise netException 
Example 30
Project: meddle   Author: glmcdona   File: SocketServer.py    License: MIT License 5 votes vote down vote up
def setup(self):
        self.connection = self.request
        if self.timeout is not None:
            self.connection.settimeout(self.timeout)
        if self.disable_nagle_algorithm:
            self.connection.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, True)
        self.rfile = self.connection.makefile('rb', self.rbufsize)
        self.wfile = self.connection.makefile('wb', self.wbufsize) 
Example 31
Project: pledgeservice   Author: MayOneUS   File: connection.py    License: Apache License 2.0 5 votes vote down vote up
def _new_conn(self):
        """ Establish a socket connection and set nodelay settings on it.

        :return: a new socket connection
        """
        extra_args = []
        if self.source_address:  # Python 2.7+
            extra_args.append(self.source_address)

        conn = socket.create_connection(
            (self.host, self.port), self.timeout, *extra_args)
        conn.setsockopt(
            socket.IPPROTO_TCP, socket.TCP_NODELAY, self.tcp_nodelay)

        return conn 
Example 32
Project: pledgeservice   Author: MayOneUS   File: connection.py    License: Apache License 2.0 5 votes vote down vote up
def _new_conn(self):
        """ Establish a socket connection and set nodelay settings on it.

        :return: a new socket connection
        """
        extra_args = []
        if self.source_address:  # Python 2.7+
            extra_args.append(self.source_address)

        conn = socket.create_connection(
            (self.host, self.port), self.timeout, *extra_args)
        conn.setsockopt(
            socket.IPPROTO_TCP, socket.TCP_NODELAY, self.tcp_nodelay)

        return conn 
Example 33
Project: azure-cli-extensions   Author: Azure   File: tunnel.py    License: MIT License 5 votes vote down vote up
def _listen(self):
        self.sock.listen(100)
        index = 0
        basic_auth_string = self.create_basic_auth()
        while True:
            self.client, _address = self.sock.accept()
            self.client.settimeout(1800)
            host = 'wss://{}{}'.format(self.remote_addr, '.scm.azurewebsites.net/AppServiceTunnel/Tunnel.ashx')
            basic_auth_header = 'Authorization: Basic {}'.format(basic_auth_string)
            cli_logger = get_logger()  # get CLI logger which has the level set through command lines
            is_verbose = any(handler.level <= logs.INFO for handler in cli_logger.handlers)
            if is_verbose:
                logger.info('Websocket tracing enabled')
                websocket.enableTrace(True)
            else:
                logger.warning('Websocket tracing disabled, use --verbose flag to enable')
                websocket.enableTrace(False)
            self.ws = create_connection(host,
                                        sockopt=((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),),
                                        class_=TunnelWebSocket,
                                        header=[basic_auth_header],
                                        sslopt={'cert_reqs': ssl.CERT_NONE},
                                        enable_multithread=True)
            logger.info('Websocket, connected status: %s', self.ws.connected)
            index = index + 1
            logger.info('Got debugger connection... index: %s', index)
            debugger_thread = Thread(target=self._listen_to_client, args=(self.client, self.ws, index))
            web_socket_thread = Thread(target=self._listen_to_web_socket, args=(self.client, self.ws, index))
            debugger_thread.start()
            web_socket_thread.start()
            logger.info('Both debugger and websocket threads started...')
            logger.warning('Successfully connected to local server..')
            debugger_thread.join()
            web_socket_thread.join()
            logger.info('Both debugger and websocket threads stopped...')
            logger.warning('Stopped local server..') 
Example 34
Project: ironpython2   Author: IronLanguages   File: SocketServer.py    License: Apache License 2.0 5 votes vote down vote up
def setup(self):
        self.connection = self.request
        if self.timeout is not None:
            self.connection.settimeout(self.timeout)
        if self.disable_nagle_algorithm:
            self.connection.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, True)
        self.rfile = self.connection.makefile('rb', self.rbufsize)
        self.wfile = self.connection.makefile('wb', self.wbufsize) 
Example 35
Project: opendevops   Author: opendevops-cn   File: iostream.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_nodelay(self, value: bool) -> None:
        if self.socket is not None and self.socket.family in (
            socket.AF_INET,
            socket.AF_INET6,
        ):
            try:
                self.socket.setsockopt(
                    socket.IPPROTO_TCP, socket.TCP_NODELAY, 1 if value else 0
                )
            except socket.error as e:
                # Sometimes setsockopt will fail if the socket is closed
                # at the wrong time.  This can happen with HTTPServer
                # resetting the value to ``False`` between requests.
                if e.errno != errno.EINVAL and not self._is_connreset(e):
                    raise 
Example 36
Project: purerpc   Author: standy66   File: grpc_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _set_socket_options(sock: anyio.SocketStream):
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        if hasattr(socket, "TCP_KEEPIDLE"):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 300)
        elif is_darwin():
            # Darwin specific option
            TCP_KEEPALIVE = 16
            sock.setsockopt(socket.IPPROTO_TCP, TCP_KEEPALIVE, 300)
        if not is_windows():
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 30)
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 
Example 37
Project: vnpy_crypto   Author: birforce   File: test_websocket.py    License: MIT License 5 votes vote down vote up
def testSockOpt(self):
        sockopt = ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),)
        s = ws.create_connection("ws://echo.websocket.org", sockopt=sockopt)
        self.assertNotEqual(s.sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY), 0)
        s.close() 
Example 38
Project: pyvisa-py   Author: pyvisa   File: tcpip.py    License: MIT License 5 votes vote down vote up
def _get_tcpip_nodelay(self, attribute):
        if self.interface:
            value = self.interface.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY)
            return (
                constants.VI_TRUE if value == 1 else constants.VI_FALSE,
                StatusCode.success,
            )
        return 0, StatusCode.error_nonsupported_attribute 
Example 39
Project: pyvisa-py   Author: pyvisa   File: tcpip.py    License: MIT License 5 votes vote down vote up
def _set_tcpip_nodelay(self, attribute, attribute_state):
        if self.interface:
            self.interface.setsockopt(
                socket.IPPROTO_TCP, socket.TCP_NODELAY, 1 if attribute_state else 0
            )
            return StatusCode.success
        return 0, StatusCode.error_nonsupported_attribute 
Example 40
Project: BinderFilter   Author: dxwu   File: SocketServer.py    License: MIT License 5 votes vote down vote up
def setup(self):
        self.connection = self.request
        if self.timeout is not None:
            self.connection.settimeout(self.timeout)
        if self.disable_nagle_algorithm:
            self.connection.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, True)
        self.rfile = self.connection.makefile('rb', self.rbufsize)
        self.wfile = self.connection.makefile('wb', self.wbufsize) 
Example 41
Project: viewfinder   Author: viewfinderco   File: iostream.py    License: Apache License 2.0 5 votes vote down vote up
def set_nodelay(self, value):
        if (self.socket is not None and
                self.socket.family in (socket.AF_INET, socket.AF_INET6)):
            try:
                self.socket.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, 1 if value else 0)
            except socket.error as e:
                # Sometimes setsockopt will fail if the socket is closed
                # at the wrong time.  This can happen with HTTPServer
                # resetting the value to false between requests.
                if e.errno != errno.EINVAL:
                    raise 
Example 42
Project: viewfinder   Author: viewfinderco   File: iostream.py    License: Apache License 2.0 5 votes vote down vote up
def set_nodelay(self, value):
        if (self.socket is not None and
                self.socket.family in (socket.AF_INET, socket.AF_INET6)):
            try:
                self.socket.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, 1 if value else 0)
            except socket.error as e:
                # Sometimes setsockopt will fail if the socket is closed
                # at the wrong time.  This can happen with HTTPServer
                # resetting the value to false between requests.
                if e.errno != errno.EINVAL:
                    raise 
Example 43
Project: ADBHoney   Author: huuck   File: core.py    License: GNU General Public License v3.0 5 votes vote down vote up
def accept_connections(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        """ Set TCP keepalive on an open socket.

            It activates after 1 second (after_idle_sec) of idleness,
            then sends a keepalive ping once every 1 seconds (interval_sec),
            and closes the connection after 100 failed ping (max_fails)
        """
        #self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # pylint: disable=no-member
        if hasattr(socket, 'TCP_KEEPIDLE'):
            self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1)
        elif hasattr(socket, 'TCP_KEEPALIVE'):
            self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPALIVE, 1)
        if hasattr(socket, 'TCP_KEEPINTVL'):
            self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 1)
        if hasattr(socket, 'TCP_KEEPCNT'):
            self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 100)
        # pylint: enable=no-member
        self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)
        self.sock.bind((self.bind_addr, self.bind_port))
        self.sock.listen(1)
        logger.info('Listening on {}:{}.'.format(self.bind_addr, self.bind_port))
        try:
            while True:
                conn, addr = self.sock.accept()
                logger.info("Received a connection, creating an ADBConnection.")
                thread = threading.Thread(target=ADBConnection, args=(conn, addr))
                thread.daemon = True
                thread.start()
        except KeyboardInterrupt:
            logger.info('Exiting...')
            self.sock.close()
            if output_writer:
                output_writer.stop() 
Example 44
Project: oss-ftp   Author: aliyun   File: SocketServer.py    License: MIT License 5 votes vote down vote up
def setup(self):
        self.connection = self.request
        if self.timeout is not None:
            self.connection.settimeout(self.timeout)
        if self.disable_nagle_algorithm:
            self.connection.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, True)
        self.rfile = self.connection.makefile('rb', self.rbufsize)
        self.wfile = self.connection.makefile('wb', self.wbufsize) 
Example 45
Project: Safejumper-for-Desktop   Author: proxysh   File: tcp.py    License: GNU General Public License v2.0 5 votes vote down vote up
def getTcpNoDelay(self):
        return operator.truth(self.socket.getsockopt(socket.IPPROTO_TCP,
                                                     socket.TCP_NODELAY)) 
Example 46
Project: Safejumper-for-Desktop   Author: proxysh   File: tcp.py    License: GNU General Public License v2.0 5 votes vote down vote up
def setTcpNoDelay(self, enabled):
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, enabled) 
Example 47
Project: Safejumper-for-Desktop   Author: proxysh   File: tcp.py    License: GNU General Public License v2.0 5 votes vote down vote up
def getTcpNoDelay(self):
        return operator.truth(self.socket.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY)) 
Example 48
Project: Safejumper-for-Desktop   Author: proxysh   File: tcp.py    License: GNU General Public License v2.0 5 votes vote down vote up
def setTcpNoDelay(self, enabled):
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, enabled) 
Example 49
Project: satori   Author: leancloud   File: connection.py    License: Apache License 2.0 5 votes vote down vote up
def _connect(self):
        "Create a TCP socket connection"
        # we want to mimic what socket.create_connection does to support
        # ipv4/ipv6, but we want to set options prior to calling
        # socket.connect()
        err = None
        for res in socket.getaddrinfo(self.host, self.port, 0,
                                      socket.SOCK_STREAM):
            family, socktype, proto, canonname, socket_address = res
            sock = None
            try:
                sock = socket.socket(family, socktype, proto)
                # TCP_NODELAY
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

                # TCP_KEEPALIVE
                if self.socket_keepalive:
                    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                    for k, v in iteritems(self.socket_keepalive_options):
                        sock.setsockopt(socket.SOL_TCP, k, v)

                # set the socket_connect_timeout before we connect
                sock.settimeout(self.socket_connect_timeout)

                # connect
                sock.connect(socket_address)

                # set the socket_timeout now that we're connected
                sock.settimeout(self.socket_timeout)
                return sock

            except socket.error as _:
                err = _
                if sock is not None:
                    sock.close()

        if err is not None:
            raise err
        raise socket.error("socket.getaddrinfo returned an empty list") 
Example 50
Project: teleport   Author: tp4a   File: iostream.py    License: Apache License 2.0 5 votes vote down vote up
def set_nodelay(self, value):
        if (self.socket is not None and
                self.socket.family in (socket.AF_INET, socket.AF_INET6)):
            try:
                self.socket.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, 1 if value else 0)
            except socket.error as e:
                # Sometimes setsockopt will fail if the socket is closed
                # at the wrong time.  This can happen with HTTPServer
                # resetting the value to false between requests.
                if e.errno != errno.EINVAL and not self._is_connreset(e):
                    raise 
Example 51
Project: teleport   Author: tp4a   File: iostream.py    License: Apache License 2.0 5 votes vote down vote up
def set_nodelay(self, value: bool) -> None:
        if self.socket is not None and self.socket.family in (
            socket.AF_INET,
            socket.AF_INET6,
        ):
            try:
                self.socket.setsockopt(
                    socket.IPPROTO_TCP, socket.TCP_NODELAY, 1 if value else 0
                )
            except socket.error as e:
                # Sometimes setsockopt will fail if the socket is closed
                # at the wrong time.  This can happen with HTTPServer
                # resetting the value to ``False`` between requests.
                if e.errno != errno.EINVAL and not self._is_connreset(e):
                    raise 
Example 52
Project: teleport   Author: tp4a   File: iostream.py    License: Apache License 2.0 5 votes vote down vote up
def set_nodelay(self, value: bool) -> None:
        if self.socket is not None and self.socket.family in (
            socket.AF_INET,
            socket.AF_INET6,
        ):
            try:
                self.socket.setsockopt(
                    socket.IPPROTO_TCP, socket.TCP_NODELAY, 1 if value else 0
                )
            except socket.error as e:
                # Sometimes setsockopt will fail if the socket is closed
                # at the wrong time.  This can happen with HTTPServer
                # resetting the value to ``False`` between requests.
                if e.errno != errno.EINVAL and not self._is_connreset(e):
                    raise 
Example 53
Project: deepWordBug   Author: QData   File: test_websocket.py    License: Apache License 2.0 5 votes vote down vote up
def testSockOpt(self):
        sockopt = ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),)
        s = ws.create_connection("ws://echo.websocket.org", sockopt=sockopt)
        self.assertNotEqual(s.sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY), 0)
        s.close() 
Example 54
Project: deepWordBug   Author: QData   File: args.py    License: Apache License 2.0 5 votes vote down vote up
def _compute_socket_options(self, scoped_config):
        # This disables Nagle's algorithm and is the default socket options
        # in urllib3.
        socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
        if scoped_config:
            # Enables TCP Keepalive if specified in shared config file.
            if self._ensure_boolean(scoped_config.get('tcp_keepalive', False)):
                socket_options.append(
                    (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1))
        return socket_options 
Example 55
Project: deepWordBug   Author: QData   File: socketserver.py    License: Apache License 2.0 5 votes vote down vote up
def setup(self):
        self.connection = self.request
        if self.timeout is not None:
            self.connection.settimeout(self.timeout)
        if self.disable_nagle_algorithm:
            self.connection.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, True)
        self.rfile = self.connection.makefile('rb', self.rbufsize)
        self.wfile = self.connection.makefile('wb', self.wbufsize) 
Example 56
Project: SenseAct   Author: kindredresearch   File: ur_communicator_delay.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_connection(host, port, disable_nagle_algorithm):
        """Establishes a TCP/IP socket connection with a UR5 controller.

        Args:
            host: a string specifying UR5 Controller IP address
            port: a string specifying UR5 Controller port
            disable_nagle_algorithm: a boolean specifying whether to
                disable nagle algorithm

        Returns:
             None or TCP socket connected to UR5 device.
        """
        sock = None
        for res in socket.getaddrinfo(host,
                                      port,
                                      socket.AF_UNSPEC,
                                      socket.SOCK_STREAM):
            afam, socktype, proto, canonname, sock_addr = res
            del canonname
            try:
                sock = socket.socket(afam, socktype, proto)
                if disable_nagle_algorithm:
                    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)
            except OSError as msg:
                print(msg)
                sock = None
                continue
            try:
                sock.connect(sock_addr)
            except OSError as msg:
                print(msg)
                sock.close()
                sock = None
                continue
            break
        return sock 
Example 57
Project: SenseAct   Author: kindredresearch   File: ur_communicator.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_connection(host, port, disable_nagle_algorithm):
        """Establishes a TCP/IP socket connection with a UR5 controller.

        Args:
            host: a string specifying UR5 Controller IP address
            port: a string specifying UR5 Controller port
            disable_nagle_algorithm: a boolean specifying whether to
                disable nagle algorithm

        Returns:
             None or TCP socket connected to UR5 device.
        """
        sock = None
        for res in socket.getaddrinfo(host,
                                      port,
                                      socket.AF_UNSPEC,
                                      socket.SOCK_STREAM):
            afam, socktype, proto, canonname, sock_addr = res
            del canonname
            try:
                sock = socket.socket(afam, socktype, proto)
                if disable_nagle_algorithm:
                    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)
            except OSError as msg:
                print(msg)
                sock = None
                continue
            try:
                sock.connect(sock_addr)
            except OSError as msg:
                print(msg)
                sock.close()
                sock = None
                continue
            break
        return sock 
Example 58
Project: tornado-zh   Author: tao12345666333   File: common.py    License: MIT License 4 votes vote down vote up
def __init__(self):
        # Based on Zope select_trigger.py:
        # https://github.com/zopefoundation/Zope/blob/master/src/ZServer/medusa/thread/select_trigger.py

        self.writer = socket.socket()
        # Disable buffering -- pulling the trigger sends 1 byte,
        # and we want that sent immediately, to wake up ASAP.
        self.writer.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

        count = 0
        while 1:
            count += 1
            # Bind to a local port; for efficiency, let the OS pick
            # a free port for us.
            # Unfortunately, stress tests showed that we may not
            # be able to connect to that port ("Address already in
            # use") despite that the OS picked it.  This appears
            # to be a race bug in the Windows socket implementation.
            # So we loop until a connect() succeeds (almost always
            # on the first try).  See the long thread at
            # http://mail.zope.org/pipermail/zope/2005-July/160433.html
            # for hideous details.
            a = socket.socket()
            a.bind(("127.0.0.1", 0))
            a.listen(1)
            connect_address = a.getsockname()  # assigned (host, port) pair
            try:
                self.writer.connect(connect_address)
                break    # success
            except socket.error as detail:
                if (not hasattr(errno, 'WSAEADDRINUSE') or
                        detail[0] != errno.WSAEADDRINUSE):
                    # "Address already in use" is the only error
                    # I've seen on two WinXP Pro SP2 boxes, under
                    # Pythons 2.3.5 and 2.4.1.
                    raise
                # (10048, 'Address already in use')
                # assert count <= 2 # never triggered in Tim's tests
                if count >= 10:  # I've never seen it go above 2
                    a.close()
                    self.writer.close()
                    raise socket.error("Cannot bind trigger!")
                # Close `a` and try again.  Note:  I originally put a short
                # sleep() here, but it didn't appear to help or hurt.
                a.close()

        self.reader, addr = a.accept()
        self.reader.setblocking(0)
        self.writer.setblocking(0)
        a.close()
        self.reader_fd = self.reader.fileno() 
Example 59
Project: tornado-zh   Author: tao12345666333   File: common.py    License: MIT License 4 votes vote down vote up
def __init__(self):
        # Based on Zope select_trigger.py:
        # https://github.com/zopefoundation/Zope/blob/master/src/ZServer/medusa/thread/select_trigger.py

        self.writer = socket.socket()
        # Disable buffering -- pulling the trigger sends 1 byte,
        # and we want that sent immediately, to wake up ASAP.
        self.writer.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

        count = 0
        while 1:
            count += 1
            # Bind to a local port; for efficiency, let the OS pick
            # a free port for us.
            # Unfortunately, stress tests showed that we may not
            # be able to connect to that port ("Address already in
            # use") despite that the OS picked it.  This appears
            # to be a race bug in the Windows socket implementation.
            # So we loop until a connect() succeeds (almost always
            # on the first try).  See the long thread at
            # http://mail.zope.org/pipermail/zope/2005-July/160433.html
            # for hideous details.
            a = socket.socket()
            a.bind(("127.0.0.1", 0))
            a.listen(1)
            connect_address = a.getsockname()  # assigned (host, port) pair
            try:
                self.writer.connect(connect_address)
                break    # success
            except socket.error as detail:
                if (not hasattr(errno, 'WSAEADDRINUSE') or
                        detail[0] != errno.WSAEADDRINUSE):
                    # "Address already in use" is the only error
                    # I've seen on two WinXP Pro SP2 boxes, under
                    # Pythons 2.3.5 and 2.4.1.
                    raise
                # (10048, 'Address already in use')
                # assert count <= 2 # never triggered in Tim's tests
                if count >= 10:  # I've never seen it go above 2
                    a.close()
                    self.writer.close()
                    raise socket.error("Cannot bind trigger!")
                # Close `a` and try again.  Note:  I originally put a short
                # sleep() here, but it didn't appear to help or hurt.
                a.close()

        self.reader, addr = a.accept()
        self.reader.setblocking(0)
        self.writer.setblocking(0)
        a.close()
        self.reader_fd = self.reader.fileno() 
Example 60
Project: recruit   Author: Frank-qlu   File: pool.py    License: Apache License 2.0 4 votes vote down vote up
def create_connection(self):
        """Connect and return a socket object.

        This is a modified version of create_connection from
        CPython >=2.6.
        """
        host, port = self.pair

        # Check if dealing with a unix domain socket
        if host.endswith('.sock'):
            if not hasattr(socket, "AF_UNIX"):
                raise ConnectionFailure("UNIX-sockets are not supported "
                                        "on this system")
            sock = socket.socket(socket.AF_UNIX)
            try:
                sock.connect(host)
                return sock
            except socket.error as e:
                if sock is not None:
                    sock.close()
                raise e

        # Don't try IPv6 if we don't support it. Also skip it if host
        # is 'localhost' (::1 is fine). Avoids slow connect issues
        # like PYTHON-356.
        family = socket.AF_INET
        if socket.has_ipv6 and host != 'localhost':
            family = socket.AF_UNSPEC

        err = None
        for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
            af, socktype, proto, dummy, sa = res
            sock = None
            try:
                sock = socket.socket(af, socktype, proto)
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE,
                                self.socket_keepalive)
                sock.settimeout(self.conn_timeout)
                sock.connect(sa)
                return sock
            except socket.error as e:
                err = e
                if sock is not None:
                    sock.close()

        if err is not None:
            raise err
        else:
            # This likely means we tried to connect to an IPv6 only
            # host with an OS/kernel or Python interpreter that doesn't
            # support IPv6. The test case is Jython2.5.1 which doesn't
            # support IPv6 at all.
            raise socket.error('getaddrinfo failed')