trsock.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import socket
  2. class TransportSocket:
  3. """A socket-like wrapper for exposing real transport sockets.
  4. These objects can be safely returned by APIs like
  5. `transport.get_extra_info('socket')`. All potentially disruptive
  6. operations (like "socket.close()") are banned.
  7. """
  8. __slots__ = ('_sock',)
  9. def __init__(self, sock: socket.socket):
  10. self._sock = sock
  11. @property
  12. def family(self):
  13. return self._sock.family
  14. @property
  15. def type(self):
  16. return self._sock.type
  17. @property
  18. def proto(self):
  19. return self._sock.proto
  20. def __repr__(self):
  21. s = (
  22. f"<asyncio.TransportSocket fd={self.fileno()}, "
  23. f"family={self.family!s}, type={self.type!s}, "
  24. f"proto={self.proto}"
  25. )
  26. if self.fileno() != -1:
  27. try:
  28. laddr = self.getsockname()
  29. if laddr:
  30. s = f"{s}, laddr={laddr}"
  31. except socket.error:
  32. pass
  33. try:
  34. raddr = self.getpeername()
  35. if raddr:
  36. s = f"{s}, raddr={raddr}"
  37. except socket.error:
  38. pass
  39. return f"{s}>"
  40. def __getstate__(self):
  41. raise TypeError("Cannot serialize asyncio.TransportSocket object")
  42. def fileno(self):
  43. return self._sock.fileno()
  44. def dup(self):
  45. return self._sock.dup()
  46. def get_inheritable(self):
  47. return self._sock.get_inheritable()
  48. def shutdown(self, how):
  49. # asyncio doesn't currently provide a high-level transport API
  50. # to shutdown the connection.
  51. self._sock.shutdown(how)
  52. def getsockopt(self, *args, **kwargs):
  53. return self._sock.getsockopt(*args, **kwargs)
  54. def setsockopt(self, *args, **kwargs):
  55. self._sock.setsockopt(*args, **kwargs)
  56. def getpeername(self):
  57. return self._sock.getpeername()
  58. def getsockname(self):
  59. return self._sock.getsockname()
  60. def getsockbyname(self):
  61. return self._sock.getsockbyname()
  62. def settimeout(self, value):
  63. if value == 0:
  64. return
  65. raise ValueError(
  66. 'settimeout(): only 0 timeout is allowed on transport sockets')
  67. def gettimeout(self):
  68. return 0
  69. def setblocking(self, flag):
  70. if not flag:
  71. return
  72. raise ValueError(
  73. 'setblocking(): transport sockets cannot be blocking')