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.

client.py 26KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. from __future__ import annotations
  2. import asyncio
  3. import functools
  4. import logging
  5. import random
  6. import urllib.parse
  7. import warnings
  8. from types import TracebackType
  9. from typing import (
  10. Any,
  11. AsyncIterator,
  12. Callable,
  13. Generator,
  14. List,
  15. Optional,
  16. Sequence,
  17. Tuple,
  18. Type,
  19. cast,
  20. )
  21. from ..datastructures import Headers, HeadersLike
  22. from ..exceptions import (
  23. InvalidHandshake,
  24. InvalidHeader,
  25. InvalidMessage,
  26. InvalidStatusCode,
  27. NegotiationError,
  28. RedirectHandshake,
  29. SecurityError,
  30. )
  31. from ..extensions import ClientExtensionFactory, Extension
  32. from ..extensions.permessage_deflate import enable_client_permessage_deflate
  33. from ..headers import (
  34. build_authorization_basic,
  35. build_extension,
  36. build_host,
  37. build_subprotocol,
  38. parse_extension,
  39. parse_subprotocol,
  40. validate_subprotocols,
  41. )
  42. from ..http import USER_AGENT
  43. from ..typing import ExtensionHeader, LoggerLike, Origin, Subprotocol
  44. from ..uri import WebSocketURI, parse_uri
  45. from .compatibility import asyncio_timeout
  46. from .handshake import build_request, check_response
  47. from .http import read_response
  48. from .protocol import WebSocketCommonProtocol
  49. __all__ = ["connect", "unix_connect", "WebSocketClientProtocol"]
  50. class WebSocketClientProtocol(WebSocketCommonProtocol):
  51. """
  52. WebSocket client connection.
  53. :class:`WebSocketClientProtocol` provides :meth:`recv` and :meth:`send`
  54. coroutines for receiving and sending messages.
  55. It supports asynchronous iteration to receive incoming messages::
  56. async for message in websocket:
  57. await process(message)
  58. The iterator exits normally when the connection is closed with close code
  59. 1000 (OK) or 1001 (going away) or without a close code. It raises
  60. a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection
  61. is closed with any other code.
  62. See :func:`connect` for the documentation of ``logger``, ``origin``,
  63. ``extensions``, ``subprotocols``, ``extra_headers``, and
  64. ``user_agent_header``.
  65. See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
  66. documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
  67. ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.
  68. """
  69. is_client = True
  70. side = "client"
  71. def __init__(
  72. self,
  73. *,
  74. logger: Optional[LoggerLike] = None,
  75. origin: Optional[Origin] = None,
  76. extensions: Optional[Sequence[ClientExtensionFactory]] = None,
  77. subprotocols: Optional[Sequence[Subprotocol]] = None,
  78. extra_headers: Optional[HeadersLike] = None,
  79. user_agent_header: Optional[str] = USER_AGENT,
  80. **kwargs: Any,
  81. ) -> None:
  82. if logger is None:
  83. logger = logging.getLogger("websockets.client")
  84. super().__init__(logger=logger, **kwargs)
  85. self.origin = origin
  86. self.available_extensions = extensions
  87. self.available_subprotocols = subprotocols
  88. self.extra_headers = extra_headers
  89. self.user_agent_header = user_agent_header
  90. def write_http_request(self, path: str, headers: Headers) -> None:
  91. """
  92. Write request line and headers to the HTTP request.
  93. """
  94. self.path = path
  95. self.request_headers = headers
  96. if self.debug:
  97. self.logger.debug("> GET %s HTTP/1.1", path)
  98. for key, value in headers.raw_items():
  99. self.logger.debug("> %s: %s", key, value)
  100. # Since the path and headers only contain ASCII characters,
  101. # we can keep this simple.
  102. request = f"GET {path} HTTP/1.1\r\n"
  103. request += str(headers)
  104. self.transport.write(request.encode())
  105. async def read_http_response(self) -> Tuple[int, Headers]:
  106. """
  107. Read status line and headers from the HTTP response.
  108. If the response contains a body, it may be read from ``self.reader``
  109. after this coroutine returns.
  110. Raises:
  111. InvalidMessage: If the HTTP message is malformed or isn't an
  112. HTTP/1.1 GET response.
  113. """
  114. try:
  115. status_code, reason, headers = await read_response(self.reader)
  116. # Remove this branch when dropping support for Python < 3.8
  117. # because CancelledError no longer inherits Exception.
  118. except asyncio.CancelledError: # pragma: no cover
  119. raise
  120. except Exception as exc:
  121. raise InvalidMessage("did not receive a valid HTTP response") from exc
  122. if self.debug:
  123. self.logger.debug("< HTTP/1.1 %d %s", status_code, reason)
  124. for key, value in headers.raw_items():
  125. self.logger.debug("< %s: %s", key, value)
  126. self.response_headers = headers
  127. return status_code, self.response_headers
  128. @staticmethod
  129. def process_extensions(
  130. headers: Headers,
  131. available_extensions: Optional[Sequence[ClientExtensionFactory]],
  132. ) -> List[Extension]:
  133. """
  134. Handle the Sec-WebSocket-Extensions HTTP response header.
  135. Check that each extension is supported, as well as its parameters.
  136. Return the list of accepted extensions.
  137. Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the
  138. connection.
  139. :rfc:`6455` leaves the rules up to the specification of each
  140. :extension.
  141. To provide this level of flexibility, for each extension accepted by
  142. the server, we check for a match with each extension available in the
  143. client configuration. If no match is found, an exception is raised.
  144. If several variants of the same extension are accepted by the server,
  145. it may be configured several times, which won't make sense in general.
  146. Extensions must implement their own requirements. For this purpose,
  147. the list of previously accepted extensions is provided.
  148. Other requirements, for example related to mandatory extensions or the
  149. order of extensions, may be implemented by overriding this method.
  150. """
  151. accepted_extensions: List[Extension] = []
  152. header_values = headers.get_all("Sec-WebSocket-Extensions")
  153. if header_values:
  154. if available_extensions is None:
  155. raise InvalidHandshake("no extensions supported")
  156. parsed_header_values: List[ExtensionHeader] = sum(
  157. [parse_extension(header_value) for header_value in header_values], []
  158. )
  159. for name, response_params in parsed_header_values:
  160. for extension_factory in available_extensions:
  161. # Skip non-matching extensions based on their name.
  162. if extension_factory.name != name:
  163. continue
  164. # Skip non-matching extensions based on their params.
  165. try:
  166. extension = extension_factory.process_response_params(
  167. response_params, accepted_extensions
  168. )
  169. except NegotiationError:
  170. continue
  171. # Add matching extension to the final list.
  172. accepted_extensions.append(extension)
  173. # Break out of the loop once we have a match.
  174. break
  175. # If we didn't break from the loop, no extension in our list
  176. # matched what the server sent. Fail the connection.
  177. else:
  178. raise NegotiationError(
  179. f"Unsupported extension: "
  180. f"name = {name}, params = {response_params}"
  181. )
  182. return accepted_extensions
  183. @staticmethod
  184. def process_subprotocol(
  185. headers: Headers, available_subprotocols: Optional[Sequence[Subprotocol]]
  186. ) -> Optional[Subprotocol]:
  187. """
  188. Handle the Sec-WebSocket-Protocol HTTP response header.
  189. Check that it contains exactly one supported subprotocol.
  190. Return the selected subprotocol.
  191. """
  192. subprotocol: Optional[Subprotocol] = None
  193. header_values = headers.get_all("Sec-WebSocket-Protocol")
  194. if header_values:
  195. if available_subprotocols is None:
  196. raise InvalidHandshake("no subprotocols supported")
  197. parsed_header_values: Sequence[Subprotocol] = sum(
  198. [parse_subprotocol(header_value) for header_value in header_values], []
  199. )
  200. if len(parsed_header_values) > 1:
  201. subprotocols = ", ".join(parsed_header_values)
  202. raise InvalidHandshake(f"multiple subprotocols: {subprotocols}")
  203. subprotocol = parsed_header_values[0]
  204. if subprotocol not in available_subprotocols:
  205. raise NegotiationError(f"unsupported subprotocol: {subprotocol}")
  206. return subprotocol
  207. async def handshake(
  208. self,
  209. wsuri: WebSocketURI,
  210. origin: Optional[Origin] = None,
  211. available_extensions: Optional[Sequence[ClientExtensionFactory]] = None,
  212. available_subprotocols: Optional[Sequence[Subprotocol]] = None,
  213. extra_headers: Optional[HeadersLike] = None,
  214. ) -> None:
  215. """
  216. Perform the client side of the opening handshake.
  217. Args:
  218. wsuri: URI of the WebSocket server.
  219. origin: Value of the ``Origin`` header.
  220. extensions: List of supported extensions, in order in which they
  221. should be negotiated and run.
  222. subprotocols: List of supported subprotocols, in order of decreasing
  223. preference.
  224. extra_headers: Arbitrary HTTP headers to add to the handshake request.
  225. Raises:
  226. InvalidHandshake: If the handshake fails.
  227. """
  228. request_headers = Headers()
  229. request_headers["Host"] = build_host(wsuri.host, wsuri.port, wsuri.secure)
  230. if wsuri.user_info:
  231. request_headers["Authorization"] = build_authorization_basic(
  232. *wsuri.user_info
  233. )
  234. if origin is not None:
  235. request_headers["Origin"] = origin
  236. key = build_request(request_headers)
  237. if available_extensions is not None:
  238. extensions_header = build_extension(
  239. [
  240. (extension_factory.name, extension_factory.get_request_params())
  241. for extension_factory in available_extensions
  242. ]
  243. )
  244. request_headers["Sec-WebSocket-Extensions"] = extensions_header
  245. if available_subprotocols is not None:
  246. protocol_header = build_subprotocol(available_subprotocols)
  247. request_headers["Sec-WebSocket-Protocol"] = protocol_header
  248. if self.extra_headers is not None:
  249. request_headers.update(self.extra_headers)
  250. if self.user_agent_header is not None:
  251. request_headers.setdefault("User-Agent", self.user_agent_header)
  252. self.write_http_request(wsuri.resource_name, request_headers)
  253. status_code, response_headers = await self.read_http_response()
  254. if status_code in (301, 302, 303, 307, 308):
  255. if "Location" not in response_headers:
  256. raise InvalidHeader("Location")
  257. raise RedirectHandshake(response_headers["Location"])
  258. elif status_code != 101:
  259. raise InvalidStatusCode(status_code, response_headers)
  260. check_response(response_headers, key)
  261. self.extensions = self.process_extensions(
  262. response_headers, available_extensions
  263. )
  264. self.subprotocol = self.process_subprotocol(
  265. response_headers, available_subprotocols
  266. )
  267. self.connection_open()
  268. class Connect:
  269. """
  270. Connect to the WebSocket server at ``uri``.
  271. Awaiting :func:`connect` yields a :class:`WebSocketClientProtocol` which
  272. can then be used to send and receive messages.
  273. :func:`connect` can be used as a asynchronous context manager::
  274. async with websockets.connect(...) as websocket:
  275. ...
  276. The connection is closed automatically when exiting the context.
  277. :func:`connect` can be used as an infinite asynchronous iterator to
  278. reconnect automatically on errors::
  279. async for websocket in websockets.connect(...):
  280. try:
  281. ...
  282. except websockets.ConnectionClosed:
  283. continue
  284. The connection is closed automatically after each iteration of the loop.
  285. If an error occurs while establishing the connection, :func:`connect`
  286. retries with exponential backoff. The backoff delay starts at three
  287. seconds and increases up to one minute.
  288. If an error occurs in the body of the loop, you can handle the exception
  289. and :func:`connect` will reconnect with the next iteration; or you can
  290. let the exception bubble up and break out of the loop. This lets you
  291. decide which errors trigger a reconnection and which errors are fatal.
  292. Args:
  293. uri: URI of the WebSocket server.
  294. create_protocol: Factory for the :class:`asyncio.Protocol` managing
  295. the connection. It defaults to :class:`WebSocketClientProtocol`.
  296. Set it to a wrapper or a subclass to customize connection handling.
  297. logger: Logger for this client.
  298. It defaults to ``logging.getLogger("websockets.client")``.
  299. See the :doc:`logging guide <../../topics/logging>` for details.
  300. compression: The "permessage-deflate" extension is enabled by default.
  301. Set ``compression`` to :obj:`None` to disable it. See the
  302. :doc:`compression guide <../../topics/compression>` for details.
  303. origin: Value of the ``Origin`` header, for servers that require it.
  304. extensions: List of supported extensions, in order in which they
  305. should be negotiated and run.
  306. subprotocols: List of supported subprotocols, in order of decreasing
  307. preference.
  308. extra_headers: Arbitrary HTTP headers to add to the handshake request.
  309. user_agent_header: Value of the ``User-Agent`` request header.
  310. It defaults to ``"Python/x.y.z websockets/X.Y"``.
  311. Setting it to :obj:`None` removes the header.
  312. open_timeout: Timeout for opening the connection in seconds.
  313. :obj:`None` disables the timeout.
  314. See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
  315. documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
  316. ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.
  317. Any other keyword arguments are passed the event loop's
  318. :meth:`~asyncio.loop.create_connection` method.
  319. For example:
  320. * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS
  321. settings. When connecting to a ``wss://`` URI, if ``ssl`` isn't
  322. provided, a TLS context is created
  323. with :func:`~ssl.create_default_context`.
  324. * You can set ``host`` and ``port`` to connect to a different host and
  325. port from those found in ``uri``. This only changes the destination of
  326. the TCP connection. The host name from ``uri`` is still used in the TLS
  327. handshake for secure connections and in the ``Host`` header.
  328. Raises:
  329. InvalidURI: If ``uri`` isn't a valid WebSocket URI.
  330. OSError: If the TCP connection fails.
  331. InvalidHandshake: If the opening handshake fails.
  332. ~asyncio.TimeoutError: If the opening handshake times out.
  333. """
  334. MAX_REDIRECTS_ALLOWED = 10
  335. def __init__(
  336. self,
  337. uri: str,
  338. *,
  339. create_protocol: Optional[Callable[..., WebSocketClientProtocol]] = None,
  340. logger: Optional[LoggerLike] = None,
  341. compression: Optional[str] = "deflate",
  342. origin: Optional[Origin] = None,
  343. extensions: Optional[Sequence[ClientExtensionFactory]] = None,
  344. subprotocols: Optional[Sequence[Subprotocol]] = None,
  345. extra_headers: Optional[HeadersLike] = None,
  346. user_agent_header: Optional[str] = USER_AGENT,
  347. open_timeout: Optional[float] = 10,
  348. ping_interval: Optional[float] = 20,
  349. ping_timeout: Optional[float] = 20,
  350. close_timeout: Optional[float] = None,
  351. max_size: Optional[int] = 2**20,
  352. max_queue: Optional[int] = 2**5,
  353. read_limit: int = 2**16,
  354. write_limit: int = 2**16,
  355. **kwargs: Any,
  356. ) -> None:
  357. # Backwards compatibility: close_timeout used to be called timeout.
  358. timeout: Optional[float] = kwargs.pop("timeout", None)
  359. if timeout is None:
  360. timeout = 10
  361. else:
  362. warnings.warn("rename timeout to close_timeout", DeprecationWarning)
  363. # If both are specified, timeout is ignored.
  364. if close_timeout is None:
  365. close_timeout = timeout
  366. # Backwards compatibility: create_protocol used to be called klass.
  367. klass: Optional[Type[WebSocketClientProtocol]] = kwargs.pop("klass", None)
  368. if klass is None:
  369. klass = WebSocketClientProtocol
  370. else:
  371. warnings.warn("rename klass to create_protocol", DeprecationWarning)
  372. # If both are specified, klass is ignored.
  373. if create_protocol is None:
  374. create_protocol = klass
  375. # Backwards compatibility: recv() used to return None on closed connections
  376. legacy_recv: bool = kwargs.pop("legacy_recv", False)
  377. # Backwards compatibility: the loop parameter used to be supported.
  378. _loop: Optional[asyncio.AbstractEventLoop] = kwargs.pop("loop", None)
  379. if _loop is None:
  380. loop = asyncio.get_event_loop()
  381. else:
  382. loop = _loop
  383. warnings.warn("remove loop argument", DeprecationWarning)
  384. wsuri = parse_uri(uri)
  385. if wsuri.secure:
  386. kwargs.setdefault("ssl", True)
  387. elif kwargs.get("ssl") is not None:
  388. raise ValueError(
  389. "connect() received a ssl argument for a ws:// URI, "
  390. "use a wss:// URI to enable TLS"
  391. )
  392. if compression == "deflate":
  393. extensions = enable_client_permessage_deflate(extensions)
  394. elif compression is not None:
  395. raise ValueError(f"unsupported compression: {compression}")
  396. if subprotocols is not None:
  397. validate_subprotocols(subprotocols)
  398. factory = functools.partial(
  399. create_protocol,
  400. logger=logger,
  401. origin=origin,
  402. extensions=extensions,
  403. subprotocols=subprotocols,
  404. extra_headers=extra_headers,
  405. user_agent_header=user_agent_header,
  406. ping_interval=ping_interval,
  407. ping_timeout=ping_timeout,
  408. close_timeout=close_timeout,
  409. max_size=max_size,
  410. max_queue=max_queue,
  411. read_limit=read_limit,
  412. write_limit=write_limit,
  413. host=wsuri.host,
  414. port=wsuri.port,
  415. secure=wsuri.secure,
  416. legacy_recv=legacy_recv,
  417. loop=_loop,
  418. )
  419. if kwargs.pop("unix", False):
  420. path: Optional[str] = kwargs.pop("path", None)
  421. create_connection = functools.partial(
  422. loop.create_unix_connection, factory, path, **kwargs
  423. )
  424. else:
  425. host: Optional[str]
  426. port: Optional[int]
  427. if kwargs.get("sock") is None:
  428. host, port = wsuri.host, wsuri.port
  429. else:
  430. # If sock is given, host and port shouldn't be specified.
  431. host, port = None, None
  432. if kwargs.get("ssl"):
  433. kwargs.setdefault("server_hostname", wsuri.host)
  434. # If host and port are given, override values from the URI.
  435. host = kwargs.pop("host", host)
  436. port = kwargs.pop("port", port)
  437. create_connection = functools.partial(
  438. loop.create_connection, factory, host, port, **kwargs
  439. )
  440. self.open_timeout = open_timeout
  441. if logger is None:
  442. logger = logging.getLogger("websockets.client")
  443. self.logger = logger
  444. # This is a coroutine function.
  445. self._create_connection = create_connection
  446. self._uri = uri
  447. self._wsuri = wsuri
  448. def handle_redirect(self, uri: str) -> None:
  449. # Update the state of this instance to connect to a new URI.
  450. old_uri = self._uri
  451. old_wsuri = self._wsuri
  452. new_uri = urllib.parse.urljoin(old_uri, uri)
  453. new_wsuri = parse_uri(new_uri)
  454. # Forbid TLS downgrade.
  455. if old_wsuri.secure and not new_wsuri.secure:
  456. raise SecurityError("redirect from WSS to WS")
  457. same_origin = (
  458. old_wsuri.host == new_wsuri.host and old_wsuri.port == new_wsuri.port
  459. )
  460. # Rewrite the host and port arguments for cross-origin redirects.
  461. # This preserves connection overrides with the host and port
  462. # arguments if the redirect points to the same host and port.
  463. if not same_origin:
  464. # Replace the host and port argument passed to the protocol factory.
  465. factory = self._create_connection.args[0]
  466. factory = functools.partial(
  467. factory.func,
  468. *factory.args,
  469. **dict(factory.keywords, host=new_wsuri.host, port=new_wsuri.port),
  470. )
  471. # Replace the host and port argument passed to create_connection.
  472. self._create_connection = functools.partial(
  473. self._create_connection.func,
  474. *(factory, new_wsuri.host, new_wsuri.port),
  475. **self._create_connection.keywords,
  476. )
  477. # Set the new WebSocket URI. This suffices for same-origin redirects.
  478. self._uri = new_uri
  479. self._wsuri = new_wsuri
  480. # async for ... in connect(...):
  481. BACKOFF_MIN = 1.92
  482. BACKOFF_MAX = 60.0
  483. BACKOFF_FACTOR = 1.618
  484. BACKOFF_INITIAL = 5
  485. async def __aiter__(self) -> AsyncIterator[WebSocketClientProtocol]:
  486. backoff_delay = self.BACKOFF_MIN
  487. while True:
  488. try:
  489. async with self as protocol:
  490. yield protocol
  491. # Remove this branch when dropping support for Python < 3.8
  492. # because CancelledError no longer inherits Exception.
  493. except asyncio.CancelledError: # pragma: no cover
  494. raise
  495. except Exception:
  496. # Add a random initial delay between 0 and 5 seconds.
  497. # See 7.2.3. Recovering from Abnormal Closure in RFC 6544.
  498. if backoff_delay == self.BACKOFF_MIN:
  499. initial_delay = random.random() * self.BACKOFF_INITIAL
  500. self.logger.info(
  501. "! connect failed; reconnecting in %.1f seconds",
  502. initial_delay,
  503. exc_info=True,
  504. )
  505. await asyncio.sleep(initial_delay)
  506. else:
  507. self.logger.info(
  508. "! connect failed again; retrying in %d seconds",
  509. int(backoff_delay),
  510. exc_info=True,
  511. )
  512. await asyncio.sleep(int(backoff_delay))
  513. # Increase delay with truncated exponential backoff.
  514. backoff_delay = backoff_delay * self.BACKOFF_FACTOR
  515. backoff_delay = min(backoff_delay, self.BACKOFF_MAX)
  516. continue
  517. else:
  518. # Connection succeeded - reset backoff delay
  519. backoff_delay = self.BACKOFF_MIN
  520. # async with connect(...) as ...:
  521. async def __aenter__(self) -> WebSocketClientProtocol:
  522. return await self
  523. async def __aexit__(
  524. self,
  525. exc_type: Optional[Type[BaseException]],
  526. exc_value: Optional[BaseException],
  527. traceback: Optional[TracebackType],
  528. ) -> None:
  529. await self.protocol.close()
  530. # ... = await connect(...)
  531. def __await__(self) -> Generator[Any, None, WebSocketClientProtocol]:
  532. # Create a suitable iterator by calling __await__ on a coroutine.
  533. return self.__await_impl_timeout__().__await__()
  534. async def __await_impl_timeout__(self) -> WebSocketClientProtocol:
  535. async with asyncio_timeout(self.open_timeout):
  536. return await self.__await_impl__()
  537. async def __await_impl__(self) -> WebSocketClientProtocol:
  538. for redirects in range(self.MAX_REDIRECTS_ALLOWED):
  539. _transport, _protocol = await self._create_connection()
  540. protocol = cast(WebSocketClientProtocol, _protocol)
  541. try:
  542. await protocol.handshake(
  543. self._wsuri,
  544. origin=protocol.origin,
  545. available_extensions=protocol.available_extensions,
  546. available_subprotocols=protocol.available_subprotocols,
  547. extra_headers=protocol.extra_headers,
  548. )
  549. except RedirectHandshake as exc:
  550. protocol.fail_connection()
  551. await protocol.wait_closed()
  552. self.handle_redirect(exc.uri)
  553. # Avoid leaking a connected socket when the handshake fails.
  554. except (Exception, asyncio.CancelledError):
  555. protocol.fail_connection()
  556. await protocol.wait_closed()
  557. raise
  558. else:
  559. self.protocol = protocol
  560. return protocol
  561. else:
  562. raise SecurityError("too many redirects")
  563. # ... = yield from connect(...) - remove when dropping Python < 3.10
  564. __iter__ = __await__
  565. connect = Connect
  566. def unix_connect(
  567. path: Optional[str] = None,
  568. uri: str = "ws://localhost/",
  569. **kwargs: Any,
  570. ) -> Connect:
  571. """
  572. Similar to :func:`connect`, but for connecting to a Unix socket.
  573. This function builds upon the event loop's
  574. :meth:`~asyncio.loop.create_unix_connection` method.
  575. It is only available on Unix.
  576. It's mainly useful for debugging servers listening on Unix sockets.
  577. Args:
  578. path: File system path to the Unix socket.
  579. uri: URI of the WebSocket server; the host is used in the TLS
  580. handshake for secure connections and in the ``Host`` header.
  581. """
  582. return connect(uri=uri, path=path, unix=True, **kwargs)