When closing a WebSocket connection, httpx-ws
can correctly send the close code, but it is unable to send the close reason.
Run following code
import anyio
import httpx_ws
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from uvicorn import Config
from uvicorn.server import Server
CODE = 1002
REASON = "Bye"
PORT = 8699
app = FastAPI()
@app.websocket("/")
async def websocket(ws: WebSocket):
await ws.accept()
await ws.send_text("Hello, world!")
try:
await ws.receive_text()
except WebSocketDisconnect as e:
print(e)
# NOTE: here we find that the close reason is not what we expected
print("is wrong reason?", e.reason != REASON)
server = Server(Config(app=app, port=PORT))
async def main():
async with httpx_ws.aconnect_ws(f"ws://127.0.0.1:{PORT}/") as ws:
print(await ws.receive_text())
await ws.close(CODE, REASON)
async with anyio.create_task_group() as tg:
tg.start_soon(server.serve)
# wait for server to start
await anyio.sleep(5)
tg.start_soon(main)
# wait for main to finish
await anyio.sleep(5)
server.should_exit = True
You can see:
(<CloseReason.PROTOCOL_ERROR: 1002>, None)
is wrong reason? True
This is a colab demo, click to run
WebSocketDisconnect
should be (1002, 'Bye')
fastapi==0.110.1 httpx-ws==0.6.0 anyio==4.3.0 uvicorn==0.29.0 hypercorn==0.16.0
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too