httpx-ws: Connection hangs forever if the WebSocket server just sends a message and close

Describe the bug

Connection hangs forever if the WebSocket server just sends a message and then close.

The client waits forever for a message, missing the only message that was sent by the server.

To Reproduce

Server code

import uvicorn
from starlette.applications import Starlette
from starlette.websockets import WebSocket
from starlette.routing import WebSocketRoute


async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    await websocket.send_text("FOO")
    await websocket.close()


routes = [
    WebSocketRoute("/ws", endpoint=websocket_endpoint),
]

app = Starlette(debug=True, routes=routes)

if __name__ == "__main__":
    uvicorn.run(app)

Client code

import httpx
from httpx_ws import connect_ws


def my_client():
    with httpx.Client() as client:
        with connect_ws("http://localhost:8000/ws", client) as ws:
            text = ws.receive_text()
            return text


if __name__ == "__main__":
    print(my_client())

Expected behavior

The client should be able to read the message and close properly.

Configuration

  • Python version: 3.7+
  • httpx-ws version: 0.1.0
  • httpx version: 0.23.1

Additional context

  • Doesn’t happen if we add an asyncio.sleep or a receive_* operation on the server side
  • Doesn’t happen with websockets library

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 25 (13 by maintainers)

Commits related to this issue

Most upvoted comments

httpcore release will happen today: https://github.com/encode/httpcore/pull/892.

@frankie567 - That’s interesting thanks. We’ve not committed to Polar yet, but I do like the work you’re/they’re doing. I’ve enabled pledges on that issue.

Thanks for the reactions!

I’ll try to work on https://github.com/encode/httpcore/issues/872 when I have some time 🙂 Subjectively, I don’t feel any urgency with this issue in httpx-ws, so I’ll refrain from creating a PR for the Private API.

Thank you @MtkN1 for the investigation and detailed explanations! That’s very impressive and appreciated 🙏 I wasn’t aware of this trailing_data mechanism. I’m of course OK to review a PR for this, even with the private API.


@tomchristie If you’re open to this, I’m ready to pledge money via Polar to help solve https://github.com/encode/httpcore/issues/872.

At that point… I just wanted to use a simple ping. 🤔