Python socket.TCP_NODELAY Examples

The following are 30 code examples of socket.TCP_NODELAY(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: wsgiserver3.py    From SalesforceXyTools with Apache License 2.0 7 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 #2
Source File: wsgiserver2.py    From SalesforceXyTools with Apache License 2.0 7 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
Source File: proxy2.py    From selenium-wire with 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 #4
Source File: test_functional.py    From oss-ftp with 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 #5
Source File: test_functional.py    From oss-ftp with 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 #6
Source File: test_functional.py    From oss-ftp with 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 #7
Source File: tcprelay.py    From neverendshadowsocks with 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 #8
Source File: posixbase.py    From Safejumper-for-Desktop with 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 #9
Source File: test_proxy2.py    From selenium-wire with 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 #10
Source File: __init__.py    From nightmare with 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
Source File: test_proxy2.py    From selenium-wire with 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 #12
Source File: test_proxy2.py    From selenium-wire with 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 #13
Source File: test_proxy2.py    From selenium-wire with 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 #14
Source File: elm.py    From ddt4all with 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 #15
Source File: test_functional.py    From oss-ftp with 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 #16
Source File: args.py    From deepWordBug with 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 #17
Source File: iostream.py    From teleport with 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 #18
Source File: tcpip.py    From pyvisa-py with 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 #19
Source File: iostream.py    From teleport with 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 #20
Source File: test_websocket.py    From deepWordBug with 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 #21
Source File: ur_communicator_delay.py    From SenseAct with 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 #22
Source File: ur_communicator.py    From SenseAct with 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 #23
Source File: iostream.py    From teleport with 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 #24
Source File: iostream.py    From viewfinder with 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 #25
Source File: iostream.py    From viewfinder with 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 #26
Source File: SocketServer.py    From BinderFilter with 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 #27
Source File: SocketServer.py    From oss-ftp with 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 #28
Source File: tcpip.py    From pyvisa-py with 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 #29
Source File: test_websocket.py    From vnpy_crypto with 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 #30
Source File: misphere.py    From pysphere with 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