websocket/_core.py¶
The _core.py file
_core.py¶
WebSocket Python client
- class websocket._core.WebSocket(get_mask_key=None, sockopt=None, sslopt=None, fire_cont_frame=False, enable_multithread=False, skip_utf8_validation=False, **_)[source]¶
Low level WebSocket interface.
This class is based on the WebSocket protocol 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()
- Parameters
get_mask_key (func) – a callable to produce new mask keys, see the set_mask_key function’s docstring for more details
sockopt (tuple) – values for socket.setsockopt. sockopt must be tuple and each element is argument of sock.setsockopt.
sslopt (dict) – optional dict object for ssl socket option.
fire_cont_frame (bool) – fire recv event for each cont frame. default is False
enable_multithread (bool) – if set to True, lock send method.
skip_utf8_validation (bool) – skip utf8 validation.
- __init__(get_mask_key=None, sockopt=None, sslopt=None, fire_cont_frame=False, enable_multithread=False, skip_utf8_validation=False, **_)[source]¶
Initialize WebSocket object.
- Parameters
sslopt (specify ssl certification verification options) –
- close(status=1000, reason=b'', timeout=3)[source]¶
Close Websocket object
- Parameters
status (int) – status code to send. see STATUS_XXX.
reason (bytes) – the reason to close.
timeout (int or float) – timeout until receive a close frame. If None, it will wait forever until receive a close frame.
- connect(url, **options)[source]¶
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: <type>
socket timeout time. This value is an integer or float. if you set None for this value, it means “use default_timeout value”
- Parameters
options –
- header: list or dict
custom http header list or dict.
- cookie: str
cookie value.
- origin: str
custom origin url.
- connection: str
custom connection header value. default value “Upgrade” set in _handshake.py
- suppress_origin: bool
suppress outputting origin header.
- host: str
custom host header string.
- http_proxy_host: <type>
http proxy host name.
- http_proxy_port: <type>
http proxy port. If not set, set to 80.
- http_no_proxy: <type>
host names, which doesn’t use proxy.
- http_proxy_auth: <type>
http proxy auth information. tuple of username and password. default is None
- redirect_limit: <type>
number of redirects to follow.
- subprotocols: <type>
array of available sub protocols. default is None.
- socket: <type>
pre-initialized stream socket.
- gettimeout()[source]¶
Get the websocket timeout (in seconds) as an int or float
- Returns
timeout – returns timeout value (in seconds). This value could be either float/integer.
- Return type
int or float
- property headers¶
Get handshake response header
- recv()[source]¶
Receive string data(byte array) from the server.
- Returns
data
- Return type
string (byte array) value.
- recv_data(control_frame=False)[source]¶
Receive data with operation code.
- Parameters
control_frame (bool) – a boolean flag indicating whether to return control frame data, defaults to False
- Returns
opcode, frame.data – tuple of operation code and string(byte array) value.
- Return type
tuple
- recv_data_frame(control_frame=False)[source]¶
Receive data with operation code.
- Parameters
control_frame (bool) – a boolean flag indicating whether to return control frame data, defaults to False
- Returns
frame.opcode, frame – tuple of operation code and string(byte array) value.
- Return type
tuple
- recv_frame()[source]¶
Receive data as frame from server.
- Returns
self.frame_buffer.recv_frame()
- Return type
ABNF frame object
- send(payload, opcode=1)[source]¶
Send the data as string.
- Parameters
payload (str) – Payload must be utf-8 string or unicode, if the opcode is OPCODE_TEXT. Otherwise, it must be string(byte array)
opcode (int) – operation code to send. Please see OPCODE_XXX.
- send_close(status=1000, reason=b'')[source]¶
Send close data to the server.
- Parameters
status (<type>) – status code to send. see STATUS_XXX.
reason (str or bytes) – the reason to close. This must be string or bytes.
- send_frame(frame)[source]¶
Send the data 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)
- Parameters
frame (ABNF frame) – frame data created by ABNF.create_frame
- set_mask_key(func)[source]¶
Set function to create mask key. You can customize mask key generator. Mainly, this is for testing purpose.
- Parameters
func (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.
- settimeout(timeout)[source]¶
Set the timeout to the websocket.
- Parameters
timeout (int or float) – timeout time (in seconds). This value could be either float/integer.
- property status¶
Get handshake status
- property subprotocol¶
Get subprotocol
- property timeout¶
Get the websocket timeout (in seconds) as an int or float
- Returns
timeout – returns timeout value (in seconds). This value could be either float/integer.
- Return type
int or float
- websocket._core.create_connection(url, timeout=None, class_=<class 'websocket._core.WebSocket'>, **options)[source]¶
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 getdefaulttimeout() 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"])
- Parameters
timeout (int or float) – socket timeout time. This value could be either float/integer. if you set None for this value, it means “use default_timeout value”
class (<type>) – 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 (<type>) –
- header: list or dict
custom http header list or dict.
- cookie: str
cookie value.
- origin: str
custom origin url.
- suppress_origin: bool
suppress outputting origin header.
- host: <type>
custom host header string.
- http_proxy_host: <type>
http proxy host name.
- http_proxy_port: <type>
http proxy port. If not set, set to 80.
- http_no_proxy: <type>
host names, which doesn’t use proxy.
- http_proxy_auth: <type>
http proxy auth information. tuple of username and password. default is None
- enable_multithread: bool
enable lock for multithread.
- redirect_limit: <type>
number of redirects to follow.
- sockopt: <type>
socket options
- sslopt: <type>
ssl option
- subprotocols: <type>
array of available sub protocols. default is None.
- skip_utf8_validation: bool
skip utf8 validation.
- socket: <type>
pre-initialized stream socket.