WebSockets
What is WebSocket?
WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. Unlike HTTP, which is a request-response protocol, WebSocket allows for persistent connections where both the client and server can send and receive messages at any time. This makes WebSocket ideal for real-time applications such as chat applications, live updates, and online gaming.
Why Use WebSocket?
- Real-Time Communication: WebSocket enables real-time data exchange between the client and server.
- Efficiency: It reduces the overhead of establishing multiple HTTP connections, making it more efficient for applications that require frequent updates.
- Bidirectional Communication: Both the client and server can initiate communication, allowing for more interactive applications.
Explanation of a WebSocket code example
Basic WebSocket code with fasthtml.
Imports and Initialization
from asyncio import sleep
*
from fasthtml.common import
= FastHTML(ws_hdr=True)
app
= app.route rt
- Imports: Imports necessary modules, including sleep from asyncio and common components from fasthtml.
- App Initialization: Initializes a FastHTML application with WebSocket support
(ws_hdr=True)
. - Route Initialization: Sets up a route handler.
Helper Function and Constants
id='msg')
def mk_inp(): return Input(
= 'notifications' nid
mk_inp
: A helper function that creates an input element with the ID msg.nid
: A constant for the notifications div ID.
Main Route
@rt('/')
async def get():
= Div(
cts
id=nid),
Div(
='form', ws_send=True),
Form(mk_inp(), id
='ws', ws_connect='/ws')
hx_ext
'Websocket Test', cts) return Titled(
- Route Definition: Defines an asynchronous route for the root URL (/).
- Content Setup: Creates a Div containing:
- Another Div with the ID nid for notifications.
- A form with an input field created by
mk_inp()
, which sends data via WebSocket (ws_send=True
). - WebSocket extension (
hx_ext='ws'
) and connection URL (ws_connect='/ws'
).
- Return: Returns a titled page with the content.
WebSocket Connection Handlers
'Hello, you have connected', id=nid))
async def on_connect(send): await send(Div(
'Disconnected!') async def on_disconnect(): print(
- on_connect: Sends a message to the client when a WebSocket connection is established.
- on_disconnect: Prints a message when the WebSocket connection is closed.
WebSocket Route
@app.ws('/ws', conn=on_connect, disconn=on_disconnect)
async def ws(msg: str, send):
'Hello ' + msg, id=nid))
await send(Div(
2)
await sleep(
'Goodbye ' + msg, id=nid), mk_inp() return Div(
- WebSocket Route: Defines a WebSocket route at /ws.
- Connection Handlers: Specifies on_connect and on_disconnect handlers.
- WebSocket Handler: An asynchronous function that:
- Receives a message (msg) from the client.
- Sends a greeting message back to the client.
- Waits for 2 seconds.
- Returns a goodbye message and a new input field.
Serve the Application
serve()
- Starts the FastHTML application.
Summary
- WebSocket: A protocol for real-time, bidirectional communication.
- Usage: Ideal for applications requiring frequent updates and real-time interaction.
- Code Functionality: Sets up a simple WebSocket application that greets the user upon connection, echoes messages, and handles disconnection.
For more details on WebSocket: - Starlette WebSocket documentation. - htmx websockets extension.