Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_socket.py 4.9KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import errno
  2. import selectors
  3. import socket
  4. from ._exceptions import *
  5. from ._ssl_compat import *
  6. from ._utils import *
  7. """
  8. _socket.py
  9. websocket - WebSocket client library for Python
  10. Copyright 2023 engn33r
  11. Licensed under the Apache License, Version 2.0 (the "License");
  12. you may not use this file except in compliance with the License.
  13. You may obtain a copy of the License at
  14. http://www.apache.org/licenses/LICENSE-2.0
  15. Unless required by applicable law or agreed to in writing, software
  16. distributed under the License is distributed on an "AS IS" BASIS,
  17. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. See the License for the specific language governing permissions and
  19. limitations under the License.
  20. """
  21. DEFAULT_SOCKET_OPTION = [(socket.SOL_TCP, socket.TCP_NODELAY, 1)]
  22. if hasattr(socket, "SO_KEEPALIVE"):
  23. DEFAULT_SOCKET_OPTION.append((socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1))
  24. if hasattr(socket, "TCP_KEEPIDLE"):
  25. DEFAULT_SOCKET_OPTION.append((socket.SOL_TCP, socket.TCP_KEEPIDLE, 30))
  26. if hasattr(socket, "TCP_KEEPINTVL"):
  27. DEFAULT_SOCKET_OPTION.append((socket.SOL_TCP, socket.TCP_KEEPINTVL, 10))
  28. if hasattr(socket, "TCP_KEEPCNT"):
  29. DEFAULT_SOCKET_OPTION.append((socket.SOL_TCP, socket.TCP_KEEPCNT, 3))
  30. _default_timeout = None
  31. __all__ = ["DEFAULT_SOCKET_OPTION", "sock_opt", "setdefaulttimeout", "getdefaulttimeout",
  32. "recv", "recv_line", "send"]
  33. class sock_opt:
  34. def __init__(self, sockopt: list, sslopt: dict) -> None:
  35. if sockopt is None:
  36. sockopt = []
  37. if sslopt is None:
  38. sslopt = {}
  39. self.sockopt = sockopt
  40. self.sslopt = sslopt
  41. self.timeout = None
  42. def setdefaulttimeout(timeout: int or float) -> None:
  43. """
  44. Set the global timeout setting to connect.
  45. Parameters
  46. ----------
  47. timeout: int or float
  48. default socket timeout time (in seconds)
  49. """
  50. global _default_timeout
  51. _default_timeout = timeout
  52. def getdefaulttimeout() -> int or float:
  53. """
  54. Get default timeout
  55. Returns
  56. ----------
  57. _default_timeout: int or float
  58. Return the global timeout setting (in seconds) to connect.
  59. """
  60. return _default_timeout
  61. def recv(sock: socket.socket, bufsize: int) -> bytes:
  62. if not sock:
  63. raise WebSocketConnectionClosedException("socket is already closed.")
  64. def _recv():
  65. try:
  66. return sock.recv(bufsize)
  67. except SSLWantReadError:
  68. pass
  69. except socket.error as exc:
  70. error_code = extract_error_code(exc)
  71. if error_code != errno.EAGAIN and error_code != errno.EWOULDBLOCK:
  72. raise
  73. sel = selectors.DefaultSelector()
  74. sel.register(sock, selectors.EVENT_READ)
  75. r = sel.select(sock.gettimeout())
  76. sel.close()
  77. if r:
  78. return sock.recv(bufsize)
  79. try:
  80. if sock.gettimeout() == 0:
  81. bytes_ = sock.recv(bufsize)
  82. else:
  83. bytes_ = _recv()
  84. except TimeoutError:
  85. raise WebSocketTimeoutException("Connection timed out")
  86. except socket.timeout as e:
  87. message = extract_err_message(e)
  88. raise WebSocketTimeoutException(message)
  89. except SSLError as e:
  90. message = extract_err_message(e)
  91. if isinstance(message, str) and 'timed out' in message:
  92. raise WebSocketTimeoutException(message)
  93. else:
  94. raise
  95. if not bytes_:
  96. raise WebSocketConnectionClosedException(
  97. "Connection to remote host was lost.")
  98. return bytes_
  99. def recv_line(sock: socket.socket) -> bytes:
  100. line = []
  101. while True:
  102. c = recv(sock, 1)
  103. line.append(c)
  104. if c == b'\n':
  105. break
  106. return b''.join(line)
  107. def send(sock: socket.socket, data: bytes) -> int:
  108. if isinstance(data, str):
  109. data = data.encode('utf-8')
  110. if not sock:
  111. raise WebSocketConnectionClosedException("socket is already closed.")
  112. def _send():
  113. try:
  114. return sock.send(data)
  115. except SSLWantWriteError:
  116. pass
  117. except socket.error as exc:
  118. error_code = extract_error_code(exc)
  119. if error_code is None:
  120. raise
  121. if error_code != errno.EAGAIN and error_code != errno.EWOULDBLOCK:
  122. raise
  123. sel = selectors.DefaultSelector()
  124. sel.register(sock, selectors.EVENT_WRITE)
  125. w = sel.select(sock.gettimeout())
  126. sel.close()
  127. if w:
  128. return sock.send(data)
  129. try:
  130. if sock.gettimeout() == 0:
  131. return sock.send(data)
  132. else:
  133. return _send()
  134. except socket.timeout as e:
  135. message = extract_err_message(e)
  136. raise WebSocketTimeoutException(message)
  137. except Exception as e:
  138. message = extract_err_message(e)
  139. if isinstance(message, str) and "timed out" in message:
  140. raise WebSocketTimeoutException(message)
  141. else:
  142. raise