API reference¶
Functions¶
- async picows.ws_connect(url: str, ws_listener_factory: Callable[[], WSListener], logger_name: str, ssl: bool | SSLContext | None = None, disconnect_on_exception: bool = True, ssl_handshake_timeout=5, ssl_shutdown_timeout=5, websocket_handshake_timeout=5, local_addr: Tuple[str, int] | None = None) Tuple[WSTransport, WSListener]¶
- Parameters:
url – Destination URL
ws_listener_factory – A parameterless factory function that returns a user handler. User handler has to derive from
WSListener.logger_name – picows will use picows.<logger_name> logger to do all the logging.
ssl – optional SSLContext to override default one when wss scheme is used
disconnect_on_exception – Indicates whether the client should initiate disconnect on any exception thrown from WSListener.on_ws* callbacks
ssl_handshake_timeout – is (for a TLS connection) the time in seconds to wait for the TLS handshake to complete before aborting the connection.
ssl_shutdown_timeout – is the time in seconds to wait for the SSL shutdown to complete before aborting the connection.
websocket_handshake_timeout – is the time in seconds to wait for the websocket server to reply to websocket handshake request
local_addr – if given, is a (local_host, local_port) tuple used to bind the socket locally. The local_host and local_port are looked up using getaddrinfo(), similarly to host and port from url.
- Returns:
WSTransportobject and a user handler returned by `ws_listener_factory()’
Open a websocket connection to a given URL.
- async picows.ws_create_server(url, ws_listener_factory, logger_name, ssl_context=None, disconnect_on_exception=True, ssl_handshake_timeout=5, ssl_shutdown_timeout=5, websocket_handshake_timeout=5, reuse_port: bool = None, start_serving: bool = False) Server¶
- Parameters:
url – Defines which interface and port to bind on and what scheme (‘ws’ or ‘wss’) to use. Currently, the path part of the URL is completely ignored.
ws_listener_factory – A parameterless factory function that returns a user handler for a newly accepted connection. User handler has to derive from
WSListener.logger_name – picows will use picows.<logger_name> logger to do all the logging.
ssl – optional SSLContext to override default one when wss scheme is used
disconnect_on_exception – Indicates whether the client should initiate disconnect on any exception thrown from WSListener.on_ws* callbacks
ssl_handshake_timeout – is (for a TLS connection) the time in seconds to wait for the TLS handshake to complete before aborting the connection.
ssl_shutdown_timeout – is the time in seconds to wait for the SSL shutdown to complete before aborting the connection.
websocket_handshake_timeout – is the time in seconds to wait for the websocket server to receive to websocket handshake request before aborting the connection.
reuse_port – tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are bound to, so long as they all set this flag when being created. This option is not supported on Windows
start_serving – causes the created server to start accepting connections immediately. When set to False, the user should await on Server.start_serving() or Server.serve_forever() to make the server to start accepting connections.
- Returns:
asyncio.Server object
Create a websocket server listening on interface and port specified by url.
Classes¶
- class picows.WSFrame¶
Received websocket frame.
Internally WSFrame just points to a chunk of memory in the receiving buffer without copying or owning memory.
Danger
Only use WSFrame object during
WSListener.on_ws_framecallback. WSFrame objects are essentially just pointers to the underlying receiving buffer. AfterWSListener.on_ws_framehas completed the buffer will be reused for the new incoming data.In order to actually copy payload use one of the get_* methods.
- fin: bool¶
Indicates whether this is the last frame of the message. Websocket messages MAY consist of multiple frames.
Unfragmented message:
WSFrame(msg_type=WSMsgType.<actual message type>, fin=True)
Fragmented message:
WSFrame(msg_type=WSMsgType.<actual message type>, fin=False) WSFrame(msg_type=WSMsgType.CONTINUATION, fin=False) ... # the last frame of the message WSFrame(msg_type=WSMsgType.CONTINUATION, fin=True)
- last_in_buffer: bool¶
Indicates whether this is the last available frame in the receiving buffer. The receiving buffer may contain more available data, but not the full frame yet.
- tail_size: int¶
Indicates how many bytes are in the receiving buffer after the current frame.
- payload_ptr: char*¶
Available only from Cython.
Raw pointer to the beginning of the frame payload in the receiving buffer.
- payload_size: size_t¶
Available only from Cython.
Size of the payload.
- get_close_code()¶
- Returns:
This method is only valid for WSMsgType.CLOSE frames.
- get_close_message()¶
- Returns:
a new bytes object with a close message. If there is no close message then returns None.
This method is only valid for WSMsgType.CLOSE frames.
- get_payload_as_ascii_text()¶
- Returns:
a new str object with a copy of frame payload.
This method will throw if payload does not contain valid ASCII 7 text.
This method does not cache results. Payload is copied and a new str object is created every time this method is called.
- get_payload_as_bytes()¶
- Returns:
a new bytes object with a copy of frame payload.
This method does not cache results. Payload is copied and a new bytes object is created every time this method is called.
- get_payload_as_memoryview()¶
- Returns:
continous memoryview to a parser buffer with payload.
Danger
Returned memoryview does NOT own the underlying memory. The content will be invalidated after
WSListener.on_ws_framehas completed. Please process payload or copy it as soon as possible.
- get_payload_as_utf8_text()¶
- Returns:
a new str object with a copy of frame payload.
This method will throw if payload does not contain valid UTF8 text.
This method does not cache results. Payload is copied and a new str object is created every time this method is called.
- class picows.WSListener¶
Base class for user handlers.
All on_ws_* methods receive transport as a first argument for convenience. It is guaranteed that passed transport object is always the same for the same connection.
- on_ws_connected(transport)¶
- Parameters:
transport –
WSTransportobject
Called after websocket handshake is complete and websocket is ready to send and receive frames.
- on_ws_disconnected(transport)¶
- Parameters:
transport –
WSTransport
Called when websocket has been disconnected.
- on_ws_frame(transport, frame)¶
- Parameters:
transport –
WSTransportobjectframe –
WSFrameobject
Called when a new frame is received.
Danger
WSFrame is essentially just a pointer to a chunk of memory in the receiving buffer. It does not own the memory. Do NOT cache or store WSFrame object for later processing because the data may be invalidated after
WSListener.on_ws_frameis complete. Process the payload immediatelly or just copy it with one of WSFrame.get_* methods.
- pause_writing()¶
Called when the underlying transport’s buffer goes over the high watermark.
- resume_writing()¶
Called when the underlying transport’s buffer drains below the low watermark.
- class picows.WSTransport¶
- send_reuse_external_buffer(WSMsgType msg_type, char* message, size_t message_size)¶
- Parameters:
msg_type – Message type
message – Pointer to a message payload
message_size – Size of the message payload
Available only from Cython.
Send a frame over websocket with a message as its payload. Don’t copy message, reuse its memory and append websocket header in front of the message
Message’s buffer should have at least 10 bytes in front of the message pointer available for writing.
- disconnect()¶
Immediately disconnect the underlying transport. It is ok to call this method multiple times. It does nothing if the transport is already disconnected.
- send(msg_type, message)¶
- Parameters:
msg_type –
WSMsgTypeenum valuemessage – an optional bytes-like object
Send a frame over websocket with a message as its payload.
- send_close(close_code=<WSCloseCode.NO_INFO: 0>, close_message=None)¶
- Parameters:
close_code –
WSCloseCodevalueclose_message – an optional bytes-like object
Send a CLOSE control frame with an optional message. This method doesn’t disconnect the underlying transport. Does nothing if the underlying transport is already disconnected.
- send_ping(message=None)¶
- Parameters:
message – an optional bytes-like object
Send a PING control frame with an optional message.
- send_pong(message=None)¶
- Parameters:
message – an optional bytes-like object
Send a PONG control frame with an optional message.
- async wait_until_closed()¶
Coroutine that conveniently allows to wait until websocket is completely closed (underlying transport is disconnected)
Enums¶
- enum picows.WSMsgType(value)¶
- Member Type:
int
Valid values are as follows:
- CONTINUATION = <WSMsgType.CONTINUATION: 0>¶
- TEXT = <WSMsgType.TEXT: 1>¶
- BINARY = <WSMsgType.BINARY: 2>¶
- PING = <WSMsgType.PING: 9>¶
- PONG = <WSMsgType.PONG: 10>¶
- CLOSE = <WSMsgType.CLOSE: 8>¶
- enum picows.WSCloseCode(value)¶
- Member Type:
int
Valid values are as follows:
- NO_INFO = <WSCloseCode.NO_INFO: 0>¶
- OK = <WSCloseCode.OK: 1000>¶
- GOING_AWAY = <WSCloseCode.GOING_AWAY: 1001>¶
- PROTOCOL_ERROR = <WSCloseCode.PROTOCOL_ERROR: 1002>¶
- UNSUPPORTED_DATA = <WSCloseCode.UNSUPPORTED_DATA: 1003>¶
- ABNORMAL_CLOSURE = <WSCloseCode.ABNORMAL_CLOSURE: 1006>¶
- INVALID_TEXT = <WSCloseCode.INVALID_TEXT: 1007>¶
- POLICY_VIOLATION = <WSCloseCode.POLICY_VIOLATION: 1008>¶
- MESSAGE_TOO_BIG = <WSCloseCode.MESSAGE_TOO_BIG: 1009>¶
- MANDATORY_EXTENSION = <WSCloseCode.MANDATORY_EXTENSION: 1010>¶
- INTERNAL_ERROR = <WSCloseCode.INTERNAL_ERROR: 1011>¶
- SERVICE_RESTART = <WSCloseCode.SERVICE_RESTART: 1012>¶
- TRY_AGAIN_LATER = <WSCloseCode.TRY_AGAIN_LATER: 1013>¶
- BAD_GATEWAY = <WSCloseCode.BAD_GATEWAY: 1014>¶