tcp_helpers.py 962 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. """Helper methods to tune a TCP connection"""
  2. import asyncio
  3. import socket
  4. from contextlib import suppress
  5. from typing import Optional # noqa
  6. __all__ = ("tcp_keepalive", "tcp_nodelay")
  7. if hasattr(socket, "SO_KEEPALIVE"):
  8. def tcp_keepalive(transport: asyncio.Transport) -> None:
  9. sock = transport.get_extra_info("socket")
  10. if sock is not None:
  11. sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
  12. else:
  13. def tcp_keepalive(transport: asyncio.Transport) -> None: # pragma: no cover
  14. pass
  15. def tcp_nodelay(transport: asyncio.Transport, value: bool) -> None:
  16. sock = transport.get_extra_info("socket")
  17. if sock is None:
  18. return
  19. if sock.family not in (socket.AF_INET, socket.AF_INET6):
  20. return
  21. value = bool(value)
  22. # socket may be closed already, on windows OSError get raised
  23. with suppress(OSError):
  24. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, value)