On this page |
This class is the base class for all websocket support in Houdini’s embedded server.
Note
WebSocket support is Python3 only.
Setup ¶
On its own the WebSocket class cannot do much of anything. The class must be registered with the server so that incoming Upgrade: websocket
requests can create an instance of the class and hand off the handling to the websocket instance. To install the instance the decorator can be used to install the websocket.
Example ¶
The below example will echo back anything sent from the client. This websocket will be used anytime a client sends a HTTP upgrade request on path /echo
.
@webSocket("/echo") class WebSocketEcho(hwebserver.WebSocket): async def connect(self, req): await self.accept() async def receive(self, text_data=None, bytes_data=None): # Send message as text data await self.send(text_data)
Methods ¶
connect(req)
→ async void
Called when the client sends a HTTP upgrade request. In this callback accept() must be called to inform the client the server has accepted the upgrade. The req
object is the HTTP request object that respresents the Upgrade request.
receive(text_data=None, bytes_data=None)
→ async void
Called on each new full websocket message. text_data
is the utf-8 text is the message was a text message. bytes_data
is the byte array if the message was a bytes message.
disconnect(code)
→ async void
Called when the websocket has been closed. No further communication should be done once this has been called. This callback is guaranteed to be called once the connection is called and its primary use is to cleanup any resources used by the websocket. code
is the close code that was used to close the websocket.
accept()
→ asyncio.Future
This must be called in the connect callback to accept the HTTP Upgrade request.
send(message, is_binary)
→ asyncio.Future
Used to send full messages back to the client. is_binary
must be True whenever a non-ascii message is to be sent.
close(close_code = 1000)
→ asyncio.Future
Close the websocket on the server side. This will inform the client that the websocket is now closed. Once the client is informed the disconnect callback is called. The default close code is 1000 (normal).
See also |