websockets
websockets copied to clipboard
WebSocket connection fails: did not receive a valid HTTP response
Attempts to connect to a WebSocket server, served by FastAPI using the websockets package, fail. But it connects perfectly using aiohttp or wscat(npm) to the same server.
A simple server:
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
A simple client:
import asyncio
import websockets
async def main():
uri = "ws://localhost/ws"
async with websockets.connect(uri) as ws:
await ws.send("hello")
print(await ws.recv())
asyncio.run(main())
The error:
➜ python main.py
Traceback (most recent call last):
File "X:\Users\SandBoxUser\AppData\Roaming\Python\Python312\site-packages\websockets\http11.py", line 241, in parse
status_line = yield from parse_line(read_line)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "X:\Users\SandBoxUser\AppData\Roaming\Python\Python312\site-packages\websockets\http11.py", line 309, in parse_line
line = yield from read_line(MAX_LINE_LENGTH)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "X:\Users\SandBoxUser\AppData\Roaming\Python\Python312\site-packages\websockets\streams.py", line 46, in read_line
raise EOFError(f"stream ends after {p} bytes, before end of line")
EOFError: stream ends after 0 bytes, before end of line
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "X:\Users\SandBoxUser\AppData\Roaming\Python\Python312\site-packages\websockets\client.py", line 301, in parse
response = yield from Response.parse(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "X:\Users\SandBoxUser\AppData\Roaming\Python\Python312\site-packages\websockets\http11.py", line 243, in parse
raise EOFError("connection closed while reading HTTP status line") from exc
EOFError: connection closed while reading HTTP status line
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "X:\Project\Project-431agent\main.py", line 228, in <module>
asyncio.run(main())
File "X:\Program Files\Python312\Lib\asyncio\runners.py", line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "X:\Program Files\Python312\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "X:\Program Files\Python312\Lib\asyncio\base_events.py", line 687, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "X:\Project\Project-431\agent\main.py", line 224, in main
async with websockets.connect(uri) as ws:
File "X:\Users\SandBoxUser\AppData\Roaming\Python\Python312\site-packages\websockets\asyncio\client.py", line 587, in __aenter__
return await self
^^^^^^^^^^
File "X:\Users\SandBoxUser\AppData\Roaming\Python\Python312\site-packages\websockets\asyncio\client.py", line 543, in __await_impl__
await self.connection.handshake(
File "X:\Users\SandBoxUser\AppData\Roaming\Python\Python312\site-packages\websockets\asyncio\client.py", line 114, in handshake
raise self.protocol.handshake_exc
websockets.exceptions.InvalidMessage: did not receive a valid HTTP response
I ran your server and client (after changing the port to 8000 which is the default port for fastapi) and it works for me:
$ python client.py
Message text was: hello
Can you paste FastAPI logs? I'm getting:
INFO 127.0.0.1:63499 - "WebSocket /ws"
INFO connection open
ERROR Exception in ASGI application
Traceback (most recent call last):
...
starlette.websockets.WebSocketDisconnect: (1000, '')
INFO connection closed
If fastapi closes the connection outright, we should see it in the logs. If we don't see anything, then the problem is probably that you aren't actually connecting to fastapi.