# WebSockets Websockets are a protocol for two-way, persistent communication between a client and server. This is different from HTTP, which uses a request/response model where the client sends a request and the server responds. With websockets, either party can send messages at any time, and the other party can respond. This allows for different applications to be built, including things like chat apps, live-updating dashboards, and real-time collaborative tools, which would require constant polling of the server for updates with HTTP. In FastHTML, you can create a websocket route using the `@app.ws` decorator. This decorator takes a route path, and optional `conn` and `disconn` parameters representing the `on_connect` and `on_disconnect` callbacks in websockets, respectively. The function decorated by `@app.ws` is the main function that is called when a message is received. Here’s an example of a basic websocket route: ``` python @app.ws('/ws', conn=on_conn, disconn=on_disconn) async def on_message(msg:str, send): await send(Div('Hello ' + msg, id='notifications')) await send(Div('Goodbye ' + msg, id='notifications')) ``` The `on_message` function is the main function that is called when a message is received and can be named however you like. Similar to standard routes, the arguments to `on_message` are automatically parsed from the websocket payload for you, so you don’t need to manually parse the message content. However, certain argument names are reserved for special purposes. Here are the most important ones: - `send` is a function that can be used to send text data to the client. - `data` is a dictionary containing the data sent by the client. - `ws` is a reference to the websocket object. For example, we can send a message to the client that just connected like this: ``` python async def on_conn(send): await send(Div('Hello, world!')) ``` Or if we receive a message from the client, we can send a message back to them: ``` python @app.ws('/ws', conn=on_conn, disconn=on_disconn) async def on_message(msg:str, send): await send(Div('You said: ' + msg, id='notifications')) # or... return Div('You said: ' + msg, id='notifications') ``` On the client side, we can use HTMX’s websocket extension to open a websocket connection and send/receive messages. For example: ``` python from fasthtml.common import * app = FastHTML(exts='ws') @app.get('/') def home(): cts = Div( Div(id='notifications'), Form(Input(id='msg'), id='form', ws_send=True), hx_ext='ws', ws_connect='/ws') return Titled('Websocket Test', cts) ``` This will create a websocket connection to the server on route `/ws`, and send any form submissions to the server via the websocket. The server will then respond by sending a message back to the client. The client will then update the message div with the message from the server using Out of Band Swaps, which means that the content is swapped with the same id without reloading the page.