How wsproto works: The Sans-I/O model
mainwsproto is a pure state-machine WebSocket implementation that does not perform any network I/O. To use it, you must implement two layers of "glue" code:
- Network Glue: You are responsible for reading bytes from a socket and passing them to the connection via
WSConnection.receive_data(data). Conversely, when you want to send data, you callWSConnection.send(event), which returns the raw bytes that you must then write to the socket. - Application Glue: You must iterate over the
WSConnection.events()generator to process high-level WebSocket events (likeTextMessageorPing) yielded by the library.
Important: If a network socket returns zero bytes (indicating a drop), call ws.receive_data(None) to update the internal state to indicate the connection has closed.
# Network Glue: Sending
bytes_to_send = ws.send(event)
sock.send(bytes_to_send)
# Network Glue: Receiving
data = sock.recv(4096)
ws.receive_data(data)
# Application Glue: Processing
for event in ws.events():
if isinstance(event, TextMessage):
print(event.data)