3 gY @@sdZddlmZddlZddlZddlZddlZddlTddlTddl Tddl Tddl Tddl Tddl TddgZGdddeZdefd dZdS) aL websocket - WebSocket client library for Python Copyright (C) 2010 Hiroki Ohtani(liris) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA )print_functionN)* WebSocketcreate_connectionc@s2eZdZdZdd)d*Zd?d+d,Zd-d.Ze e!j"d"fd/d0Z#e e!j"d"d1fd2d3Z$d4d5Z%d6d7Z&d8d9Z'd:d;Z(dS)@ra Low level WebSocket interface. This class is based on The WebSocket protocol draft-hixie-thewebsocketprotocol-76 http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 We can connect to the websocket server and send/receive data. The following example is an echo client. >>> import websocket >>> ws = websocket.WebSocket() >>> ws.connect("ws://echo.websocket.org") >>> ws.send("Hello, Server") >>> ws.recv() 'Hello, Server' >>> ws.close() get_mask_key: a callable to produce new mask keys, see the set_mask_key function's docstring for more details sockopt: values for socket.setsockopt. sockopt must be tuple and each element is argument of sock.setsockopt. sslopt: dict object for ssl socket option. fire_cont_frame: fire recv event for each cont frame. default is False enable_multithread: if set to True, lock send method. skip_utf8_validation: skip utf8 validation. NFcKsZt|||_d|_d|_d|_||_t|j||_t|||_|rNt j |_ nt |_ dS)z. Initialize WebSocket object. NF) sock_opthandshake_responsesock connected get_mask_key frame_buffer_recvcontinuous_frame cont_frame threadingLocklockNoLock)selfr sockoptssloptfire_cont_frameenable_multithreadskip_utf8_validation_r@/Users/olari/OneDrive/sandbox/awsBlog2/lambda/websocket/_core.py__init__Ns   zWebSocket.__init__ccsx|jVqWdS)zX Allow iteration over websocket, implying sequential `recv` executions. N)recv)rrrr__iter__dszWebSocket.__iter__cCs|jS)N)r)rrrr__next__kszWebSocket.__next__cCs|jS)N)r )rrrrnextnszWebSocket.nextcCs |jjS)N)r fileno)rrrrr"qszWebSocket.filenocCs ||_dS)aj set function to create musk key. You can customize mask key generator. Mainly, this is for testing purpose. func: callable object. the func takes 1 argument as integer. The argument means length of mask key. This func must return string(byte array), which length is argument specified. N)r )rfuncrrr set_mask_keyts zWebSocket.set_mask_keycCs|jjS)z4 Get the websocket timeout(second). )rtimeout)rrrr gettimeoutszWebSocket.gettimeoutcCs||j_|jr|jj|dS)z[ Set the timeout to the websocket. timeout: timeout time(second). N)rr%r settimeout)rr%rrrr'szWebSocket.settimeoutcCs|jr|jjSdSdS)z! get subprotocol N)r subprotocol)rrrrgetsubprotocolszWebSocket.getsubprotocolcCs|jr|jjSdSdS)z& get handshake status N)rstatus)rrrr getstatusszWebSocket.getstatuscCs|jr|jjSdSdS)z/ get handshake response header N)rheaders)rrrr getheadersszWebSocket.getheadersc Kslt||jtf||jdd\|_}yt|jf|||_d|_Wn$|jr`|jjd|_YnXdS)aQ Connect to url. url is websocket url scheme. ie. ws://host:port/resource You can customize using 'options'. If you set "header" list object, you can set your own custom header. >>> ws = WebSocket() >>> ws.connect("ws://echo.websocket.org/", ... header=["User-Agent: MyProgram", ... "x-custom: header"]) timeout: socket timeout time. This value is integer. if you set None for this value, it means "use default_timeout value" options: "header" -> custom http header list or dict. "cookie" -> cookie value. "origin" -> custom origin url. "host" -> custom host header string. "http_proxy_host" - http proxy host name. "http_proxy_port" - http proxy port. If not set, set to 80. "http_no_proxy" - host names, which doesn't use proxy. "http_proxy_auth" - http proxy auth information. tuple of username and password. default is None "subprotocols" - array of available sub protocols. default is None. "socket" - pre-initialized stream socket. socketNT) connectrZ proxy_infopopr Z handshakerr close)rurloptionsaddrsrrrr/s  zWebSocket.connectcCstj||}|j|S)a Send the data as string. payload: Payload must be utf-8 string or unicode, if the opcode is OPCODE_TEXT. Otherwise, it must be string(byte array) opcode: operation code to send. Please see OPCODE_XXX. )ABNF create_frame send_frame)rpayloadopcodeframerrrsends zWebSocket.sendc Csd|jr|j|_|j}t|}tdt||j&x|rT|j|}||d}q8WWdQRX|S)a Send the data frame. frame: frame data created by ABNF.create_frame >>> ws = create_connection("ws://echo.websocket.org/") >>> frame = ABNF.create_frame("Hello", ABNF.OPCODE_TEXT) >>> ws.send_frame(frame) >>> cont_frame = ABNF.create_frame("My name is ", ABNF.OPCODE_CONT, 0) >>> ws.send_frame(frame) >>> cont_frame = ABNF.create_frame("Foo Bar", ABNF.OPCODE_CONT, 1) >>> ws.send_frame(frame) zsend: N)r formatlentracereprr_send)rr:datalengthlrrrr7s zWebSocket.send_framecCs|j|tjS)N)r;r5 OPCODE_BINARY)rr8rrr send_binaryszWebSocket.send_binarycCs(t|tjr|jd}|j|tjdS)zP send ping data. payload: data payload to send server. zutf-8N) isinstancesix text_typeencoder;r5 OPCODE_PING)rr8rrrping s  zWebSocket.pingcCs(t|tjr|jd}|j|tjdS)zP send pong data. payload: data payload to send server. zutf-8N)rGrHrIrJr;r5 OPCODE_PONG)rr8rrrpongs  zWebSocket.pongcCsF|j\}}tjr&|tjkr&|jdS|tjks:|tjkr>|SdSdS)zs Receive string data(byte array) from the server. return value: string(byte array) value. zutf-8rFN) recv_datarHPY3r5 OPCODE_TEXTdecoderD)rr9rArrrrs   zWebSocket.recvcCs|j|\}}||jfS)z Receive data with operation code. control_frame: a boolean flag indicating whether to return control frame data, defaults to False return value: tuple of operation code and string(byte array) value. )recv_data_framerA)r control_framer9r:rrrrO-s zWebSocket.recv_datacCsx|j}|std|q|jtjtjtjfkrd|jj||jj ||jj |r|jj |Sq|jtj kr|j |j|fS|jtjkrt|jdkr|j|jntd|r|j|fSq|jtjkr|r|j|fSqWdS)z Receive data with operation code. control_frame: a boolean flag indicating whether to return control frame data, defaults to False return value: tuple of operation code and string(byte array) value. zNot a valid frame %s~zPing message is too longN) recv_frameWebSocketProtocolExceptionr9r5rQrD OPCODE_CONTrvalidateaddis_fireextract OPCODE_CLOSE send_closerKr=rArNrM)rrTr:rrrrS9s.          zWebSocket.recv_data_framecCs |jjS)z^ receive data as frame from server. return value: ABNF frame object. )r rV)rrrrrV_szWebSocket.recv_framecCs>|dks|tjkrtdd|_|jtjd||tjdS)z send close data to the server. status: status code to send. see STATUS_XXX. reason: the reason to close. This must be string or bytes. rzcode is invalid rangeFz!HN)r5 LENGTH_16 ValueErrorr r;structpackr])rr*reasonrrrr^gszWebSocket.send_closecCs|jr|dks|tjkr tdyd|_|jtjd||tj|jj }|jj |y<|j }t rtj d|jd}|tkrtdt|Wn YnX|jj ||jjtjWn YnX|jdS)a Close Websocket object status: status code to send. see STATUS_XXX. reason: the reason to close. This must be string. timeout: timeout until receive a close frame. If None, it will wait forever until receive a close frame. rzcode is invalid rangeFz!Hzclose status: N)r r5r_r`r;rarbr]r r&r'rVZisEnabledForErrorunpackrA STATUS_NORMALerrorr?shutdownr. SHUT_RDWR)rr*rcr%Z sock_timeoutr:Z recv_statusrrrr1ts,     zWebSocket.closecCs|jr|jjtjdS)za Low-level asynchronous abort, wakes up other threads that are waiting in recv_* N)r r rhr.ri)rrrrabortszWebSocket.abortcCs |jr|jjd|_d|_dS)zclose socket, immediately.NF)r r1r )rrrrrhs zWebSocket.shutdowncCs t|j|S)N)r;r )rrArrrr@szWebSocket._sendc CsDy t|j|Stk r>|jr,|jjd|_d|_YnXdS)NF)rr "WebSocketConnectionClosedExceptionr1r )rbufsizerrrr s  zWebSocket._recv)NNNFFF)rF)F)F))__name__ __module__ __qualname____doc__rrr r!r"r$r&r'propertyr%r)r(r+r*r-r,r/r5rQr;r7rErLrNrrOrSrVrfrHbr^r1rjrhr@r rrrrr2sD      +   & $c Ks|jdg}|jdi}|jdd}|jdd}|jdd}|f|||||d|} | j|dk rf|nt| j|f|| S) aY connect to url and return websocket object. Connect to url and return the WebSocket object. Passing optional timeout parameter will set the timeout on the socket. If no timeout is supplied, the global default timeout setting returned by getdefauttimeout() is used. You can customize using 'options'. If you set "header" list object, you can set your own custom header. >>> conn = create_connection("ws://echo.websocket.org/", ... header=["User-Agent: MyProgram", ... "x-custom: header"]) timeout: socket timeout time. This value is integer. if you set None for this value, it means "use default_timeout value" class_: class to instantiate when creating the connection. It has to implement settimeout and connect. It's __init__ should be compatible with WebSocket.__init__, i.e. accept all of it's kwargs. options: "header" -> custom http header list or dict. "cookie" -> cookie value. "origin" -> custom origin url. "host" -> custom host header string. "http_proxy_host" - http proxy host name. "http_proxy_port" - http proxy port. If not set, set to 80. "http_no_proxy" - host names, which doesn't use proxy. "http_proxy_auth" - http proxy auth information. tuple of username and password. default is None "enable_multithread" -> enable lock for multithread. "sockopt" -> socket options "sslopt" -> ssl option "subprotocols" - array of available sub protocols. default is None. "skip_utf8_validation" - skip utf8 validation. "socket" - pre-initialized stream socket. rrrFrr)rrrrrN)r0r'getdefaulttimeoutr/) r2r%Zclass_r3rrrrrZwebsockrrrrs)     )rp __future__rr.rarrH_abnf _exceptionsZ _handshake_http_logging_socket_utils__all__objectrrrrrrs$