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.
 
 
 
 

706 line
26 KiB

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