K ixXXddlmZddlZddlZddlZddlZddlmZddl m Z m Z m Z m Z mZddlmZddlmZmZddlmZmZmZdd lmZdd lmZdd lmZmZmZdd l m!Z!m"Z"dd l#m$Z$m%Z%ddl&m'Z'ddl m(Z(m)Z)m*Z*ddl+m,Z,m-Z-m.Z.m/Z/m0Z0ddl1m2Z2ddl3m4Z4gdZ5Gdde2Z6dddddddde!dddddddddddd d0dZ7 d1 d2dZ8 dd l9m:Z:dd!l;m,Z<e:jze:jze:j|e:j|d"Z?dd#dd#d"Z@ d3d$ZA d4 d5d&ZCd6d'ZDdddd( d7d)ZEe d*ZFe d+e d,eFf-ZGGd.d/ZHy#eB$r d3d%ZAY`wxYw)8) annotationsN)Sequence)AnyCallableLiteralTypeVarcast)ClientProtocol)Headers HeadersLike)InvalidProxyMessageInvalidProxyStatus ProxyError)ClientExtensionFactory) enable_client_permessage_deflate)build_authorization_basic build_hostvalidate_subprotocols) USER_AGENTResponse) CONNECTINGEvent) StreamReader) LoggerLikeOrigin Subprotocol)Proxy WebSocketURI get_proxy parse_proxy parse_uri) Connection)Deadline)connect unix_connectClientConnectionceZdZdZddddd d fdZdedf d dZd fd Zdfd ZxZ S)r(a1 :mod:`threading` implementation of a WebSocket client connection. :class:`ClientConnection` provides :meth:`recv` and :meth:`send` methods for receiving and sending messages. It supports iteration to receive messages:: for message in websocket: process(message) The iterator exits normally when the connection is closed with close code 1000 (OK) or 1001 (going away) or without a close code. It raises a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is closed with any other code. The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and ``max_queue`` arguments have the same meaning as in :func:`connect`. Args: socket: Socket connected to a WebSocket server. protocol: Sans-I/O connection.   ping_interval ping_timeout close_timeout max_queuecf|tj|_t|||||||y)Nr-) threadingr response_rcvdsuper__init__)selfsocketprotocolr.r/r0r1 __class__s \/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/websockets/sync/client.pyr6zClientConnection.__init__6s; &__.   '%'  Nc$|jt5|jj|_|%|jj j ||&|jj jd||jj|jddd|jj|s td|jj|jjy#1swY\xYw)z1 Perform the opening handshake. )expected_stateN User-Agentz.timed out while waiting for handshake response) send_contextrr9r&requestheadersupdate setdefault send_requestr4wait TimeoutError handshake_exc)r7additional_headersuser_agent_headertimeouts r; handshakezClientConnection.handshakeKs  j  9 5==002DL!- $$++,>? , $$// >OP MM & &t|| 4  5!!&&w/OP P == & & 2---- - 3 5 5s BDDc|j4t|tsJ||_|jj yt ||y)z. Process one incoming event. N)response isinstancerr4setr5 process_event)r7eventr:s r;rQzClientConnection.process_eventgsG == eX. ..!DM    " " $ G !% (r<c t||jjy#|jjwxYw)zI Read incoming data from the socket and process events. N)r5 recv_eventsr4rP)r7r:s r;rTzClientConnection.recv_eventsus:  % G  !    " " $D   " " $s ,A)r8 socket.socketr9r r. float | Noner/rVr0rVr1*int | None | tuple[int | None, int | None]returnNone)rIHeadersLike | NonerJ str | NonerKrVrXrY)rRrrXrY)rXrY) __name__ __module__ __qualname____doc__r6rrLrQrT __classcell__)r:s@r;r(r(s<')%'&(@B  ! $  #  $ >   .26(2 $ ...&. .  .8 ) % %r<r(deflateTr+r*ir,)socksslserver_hostnameorigin extensions subprotocols compressionrIrJproxy proxy_sslproxy_server_hostname open_timeoutr.r/r0max_sizer1loggercreate_connectionc |/d|vr+|jd}tjdtt |}|j s | t d|jdd}|jdd}|r| | t d| | t d | t||d k(r t|}n|t d ||rd} |d} | d ur t|} t| }|t} |Q|rgtjtjtj}|j|j!|J|j#|n| t%| }|j&dd dk(r t)||||jdd}n|j&dddk(r/|j&dk7r | t dt+|||f| | | d|}nWt-d|j/d|j!tj0|j2|j4ffi|}|jd|s/|j7tj8tj:d |j r|t=j>}| |j2}|j|j!| |jA||}n(tC|||}tEtj|}|jdtG||||||}|||||||} |jM|| |j!|jU|S#tH$r||jKwxYw#tH$r,|jO|jPjSwxYw)a Connect to the WebSocket server at ``uri``. This function returns a :class:`ClientConnection` instance, which you can use to send and receive messages. :func:`connect` may be used as a context manager:: from websockets.sync.client import connect with connect(...) as websocket: ... The connection is closed automatically when exiting the context. Args: uri: URI of the WebSocket server. sock: Preexisting TCP socket. ``sock`` overrides the host and port from ``uri``. You may call :func:`socket.create_connection` to create a suitable TCP socket. ssl: Configuration for enabling TLS on the connection. server_hostname: Host name for the TLS handshake. ``server_hostname`` overrides the host name from ``uri``. origin: Value of the ``Origin`` header, for servers that require it. extensions: List of supported extensions, in order in which they should be negotiated and run. subprotocols: List of supported subprotocols, in order of decreasing preference. compression: The "permessage-deflate" extension is enabled by default. Set ``compression`` to :obj:`None` to disable it. See the :doc:`compression guide <../../topics/compression>` for details. additional_headers (HeadersLike | None): Arbitrary HTTP headers to add to the handshake request. user_agent_header: Value of the ``User-Agent`` request header. It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to :obj:`None` removes the header. proxy: If a proxy is configured, it is used by default. Set ``proxy`` to :obj:`None` to disable the proxy or to the address of a proxy to override the system configuration. See the :doc:`proxy docs <../../topics/proxies>` for details. proxy_ssl: Configuration for enabling TLS on the proxy connection. proxy_server_hostname: Host name for the TLS handshake with the proxy. ``proxy_server_hostname`` overrides the host name from ``proxy``. open_timeout: Timeout for opening the connection in seconds. :obj:`None` disables the timeout. ping_interval: Interval between keepalive pings in seconds. :obj:`None` disables keepalive. ping_timeout: Timeout for keepalive pings in seconds. :obj:`None` disables timeouts. close_timeout: Timeout for closing the connection in seconds. :obj:`None` disables the timeout. max_size: Maximum size of incoming messages in bytes. :obj:`None` disables the limit. max_queue: High-water mark of the buffer where frames are received. It defaults to 16 frames. The low-water mark defaults to ``max_queue // 4``. You may pass a ``(high, low)`` tuple to set the high-water and low-water marks. If you want to disable flow control entirely, you may set it to ``None``, although that's a bad idea. logger: Logger for this client. It defaults to ``logging.getLogger("websockets.client")``. See the :doc:`logging guide <../../topics/logging>` for details. create_connection: Factory for the :class:`ClientConnection` managing the connection. Set it to a wrapper or a subclass to customize connection handling. Any other keyword arguments are passed to :func:`~socket.create_connection`. Raises: InvalidURI: If ``uri`` isn't a valid WebSocket URI. OSError: If the TCP connection fails. InvalidHandshake: If the opening handshake fails. TimeoutError: If the opening handshake times out. N ssl_contextzssl_context was renamed to sslz-ssl argument is incompatible with a ws:// URIunixFpathzmissing path argumentz(path and sock arguments are incompatiblerazunsupported compression: Tsockssource_address) local_addrhttphttpsz8proxy_ssl argument is incompatible with an http:// proxyrJrcrdzunsupported proxyrKrd)rerfrgrmrnr-)+popwarningswarnDeprecationWarningr"secure ValueErrorrrr r%r(r8AF_UNIX SOCK_STREAM settimeoutrKr&r!schemeconnect_socks_proxyconnect_http_proxyAssertionErrorrDrohostport setsockopt IPPROTO_TCP TCP_NODELAY ssl_modulecreate_default_context wrap_socket SSLSSLSocketr r ExceptioncloserL close_socketrecv_events_threadjoinstart_keepalive)urirbrcrdrerfrgrhrIrJrirjrkrlr.r/r0rmr1rnrokwargsws_urirrrsdeadline proxy_parsedsock_2r9 connections r;r&r&s\ {}.jj' ,  s^F ==S_HIIFE*Dzz&$/D #E D"((!,6#**g5):O(V.$ +<%(= !D))<==!!)X-=-=-?@//[[&++. OOD ! OOF..0B0BD I =={ 779&"(++ OOH,,. / t_M%dCQFMM62 OOD !" !%  '  '%'           #    JJL  !%%**, s3IM)6!N )N 5N>c r|'|jd|jdd}nd}td|d|d|S)a Connect to a WebSocket server listening on a Unix socket. This function accepts the same keyword arguments as :func:`connect`. It's only available on Unix. It's mainly useful for debugging servers listening on Unix sockets. Args: path: File system path to the Unix socket. uri: URI of the WebSocket server. ``uri`` defaults to ``ws://localhost/`` or, when a ``ssl`` is provided, to ``wss://localhost/``. rcrqzws://localhost/zwss://localhost/T)rrrrs)getr&)rsrrs r;r'r'sG* { ::e  $M)B)J#C$C  ;sD ;F ;;r<) ProxyType)r)socks5hsocks5socks4asocks4Fc tt|j|j|j|j |j t|j}|jd|j |j|j|jfi|S#tttjf$rt$r}td|d}~wwxYw)z0Connect via a SOCKS proxy and return the socket.rKz failed to connect to SOCKS proxyN) SocksProxySOCKS_PROXY_TYPESrrrusernamepasswordSOCKS_PROXY_RDNSrDrKr&OSErrorrGr8rr)rirrr socks_proxyexcs r;rrs! ell + JJ JJ NN NN U\\ *   )X%5%5%78 J&;&&v{{FKKJ6J Jv~~6   J?@c I Js<'B$$'C CCc td)Nz-python-socks is required to use a SOCKS proxy) ImportError)rirrrs r;rrs IJJr<ct|j|j|jd}t }t|j|j|j|d<|||d<|j 1|j Jt|j |j |d<d|dj|jzS)NT)always_include_portHostr?zProxy-AuthorizationzCONNECT z HTTP/1.1 ) rrrrr rrrencode serialize)rirrJrrBs r;prepare_connect_requestrs fkk6;; SW XDiG fkk6==IGFO$ 1  ~~!~~))))B NNENN* %&dV= ) 0 0 2W5F5F5H HHr<ct}tj|j|j|j d} |j |j|jd}|r|j|n|jt|`#t$rr}t|jtsJ|j}d|jcxkrdkr%n t!||cYd}~|j dSt!|d}~wt"j$r t%dt&$r}t)d|d}~wwxYw#|j dwxYw)NF) include_bodyii,z(timed out while connecting to HTTP proxyz0did not receive a valid HTTP response from proxy)rrparse read_line read_exact read_to_eofrrKrecv feed_datafeed_eofnext StopIterationrOvalue status_coderr8rGrr)rbrreaderparserdatarrNs r;read_connect_responsers; ^F ^^ F  OOH,,. /99T?D  &! L /#))X...99 (&& , ,%X. .O %X. . >>GEFF ! >   sDA!B$$ E-A D8E9E D)E EEEE*r{c |jd|jtj|j|j ffi|}|j dk(rg|tj}| |j}|j|j|j||}|jd|jt||| t|||S#t$r|jwxYw)NrKrzr|)rDrKr8rorrrrrrrsendallrrrr)rirrrJrcrdrrbs r;rrs i!1!1!34  # #UZZ$< G GD ||w ;335C  "#jjO ((*+t_E  LL(8IJKdH- K   s C..D TF.)boundcVeZdZdZdZ d d dZd dZd dZddZddZ dd Z y)rzr Socket-like object providing TLS-in-TLS. Only methods that are used by websockets are implemented. iNctj|_tj|_||_|j |j|j||_|j|j jy)Nr|) r MemoryBIOincomingoutgoing ssl_socketwrap_bio ssl_objectrun_io do_handshake)r7rbrqrds r;r6zSSLSSLSocket.__init__Esk #,,. ",,. %.. MM MM+/  DOO001r<c d}d} ||}|jj }|r|j j ||r^|j j|j}|r|jj|n|jj|rS#tj$rd}Ytj$rd}YwxYw)NTF) rSSLWantReadErrorSSLWantWriteErrorrreadrrr recv_bufsizerwrite write_eof)r7funcargs want_read want_writeresultrs r;rzSSLSSLSocket.run_ioUsIJ "t==%%'D''-++D,=,=>MM''-MM++-M-.. ! // "!  "sB((C?CCc |j|jj|S#tj$rYywxYw)Nr<)rrrr SSLEOFError)r7buflens r;rzSSLSSLSocket.recvss: ;;t33V< <%%  s %(>>cN|j|jj|SN)rrr)r7rs r;sendzSSLSSLSocket.sendys{{4??00$77r<cd}t|5}|jd5}t|}||kr||j||dz }||krddddddy#1swYxYw#1swYyxYw)NrB) memoryviewr lenr)r7rcountview byte_viewamounts r;rzSSLSSLSocket.sendall|sz   6tyy~ 6^F&.9UV#455&. 6 6 6 6 6 6s"A+-AA+A( $A++A4c.t|j|Sr)getattrr)r7names r; __getattr__zSSLSSLSocket.__getattr__st--r<r)rbrUrqzssl_module.SSLContextrdr[rXrY)rzCallable[..., T]rrrXr)rintrXbytes)rrrXr)rrrXrY)rstrrXr) r\r]r^r_rr6rrrrrrr<r;rr;sWL '+ 22+2$ 2  2 < 86.r<r).rrrbzsocket.socket | Nonercssl_module.SSLContext | Nonerdr[rez Origin | Nonerfz'Sequence[ClientExtensionFactory] | NonergzSequence[Subprotocol] | Nonerhr[rIrZrJr[rizstr | Literal[True] | Nonerjrrkr[rlrVr.rVr/rVr0rVrmz int | Noner1rWrnzLoggerLike | Noneroztype[ClientConnection] | NonerrrXr()NN)rsr[rr[rrrXr() rirrrrr%rrrXrUr)rirrrrJr[rXr)rbrUrr%rXr)rirrrrr%rJr[rcrrdr[rrrXrU)I __future__rr8rcrr3r~collections.abcrtypingrrrrr clientr datastructuresr r exceptionsrrrextensions.baserextensions.permessage_deflaterrBrrrhttp11rrr9rrstreamsrrrrrrrr r!r"rr$utilsr%__all__r(r&r' python_socksrpython_socks.syncrSOCKS5SOCKS4rrrrrrrrrrrr<r;r sp" $88#1LL4LRR)("44HH" :b%zb%R"&(,"& :>15'-1$.(,.2(,!#"$!#"$ <> $7;;D D  D & D  D D8D/DD+D"D &D ,!D"&#D&'D( )D*+D, -D01D2:3D6 7D:5;D<=D>?DP< < << <<3K&5##""##""  JJJJ J  JN%)I I I"I I&N%)(,"&# # ## " # & # ###L CL CxQ'(M.M.UKKKKK K  KKs8AFF)(F)