From bea3a4247a450be7fb82dec111429bb2752aac4d Mon Sep 17 00:00:00 2001 From: Yury Selivanov Date: Tue, 5 Jul 2016 19:28:43 -0400 Subject: [PATCH] Set TCP_NODELAY on TCP transports by default --- asyncio/selector_events.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/asyncio/selector_events.py b/asyncio/selector_events.py index c57f509a..c91ab04f 100644 --- a/asyncio/selector_events.py +++ b/asyncio/selector_events.py @@ -39,6 +39,17 @@ def _test_selector_event(selector, fd, event): return bool(key.events & event) +if hasattr(socket, 'TCP_NODELAY'): + def _set_nodelay(sock): + if (sock.family in {socket.AF_INET, socket.AF_INET6} and + sock.type == socket.SOCK_STREAM and + sock.proto == socket.IPPROTO_TCP): + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) +else: + def _set_nodelay(sock): + pass + + class BaseSelectorEventLoop(base_events.BaseEventLoop): """Selector event loop. @@ -640,6 +651,11 @@ def __init__(self, loop, sock, protocol, waiter=None, self._eof = False self._paused = False + # Disable the Nagle algorithm -- small writes will be + # sent without waiting for the TCP ACK. This generally + # decreases the latency (in some cases significantly.) + _set_nodelay(self._sock) + self._loop.call_soon(self._protocol.connection_made, self) # only start reading when connection_made() has been called self._loop.call_soon(self._loop.add_reader,