[Python] How to connect to websocket FastAPI Socketio

Discussão em 'Python' iniciado por Stack, Agosto 9, 2025.

  1. Stack

    Stack Membro Participativo

    ws.py

    from loguru import logger
    import socketio
    from typing import List

    def handle_connect(sid, environ):
    logger.info(f"Socket connected with sid {sid}")

    class SocketManager:
    def __init__(self, origins: List[str]):
    self.server = socketio.AsyncServer(
    cors_allowed_origins=origins,
    async_mode="asgi",
    logger=True,
    engineio_logger=True,
    )
    self.app = socketio.ASGIApp(self.server)

    @property
    def on(self):
    return self.server.on

    @property
    def send(self):
    return self.server.send

    def mount_to(self, path: str, app: socketio.ASGIApp):
    app.mount(path, self.app)


    socket_manager = SocketManager(origins=["*"])
    socket_manager.on("connect", handler=handle_connect)


    main.py

    from ws import socket_manager

    app = FastAPI(
    title="MyBackend",
    docs_url="/docs",
    openapi_url="/openapi.json"
    )

    app.include_router(router, prefix="/api/v1")
    socket_manager.mount_to("/ws", app)


    Getting next error through dev console: WebSocket connection to 'ws://localhost:80/ws/' failed

    In python:

    RuntimeError: Expected ASGI message 'websocket.accept' or 'websocket.close', but got 'http.response.start'.
    DEBUG: > HTTP/1.1 101 Switching Protocols
    DEBUG: > Upgrade: websocket
    DEBUG: > Connection: Upgrade
    DEBUG: > Sec-WebSocket-Accept: TDJXRnQoVA7XR0L7D7yn+va91Q4=
    DEBUG: > Sec-WebSocket-Extensions: permessage-deflate
    DEBUG: > date: Sun, 26 Feb 2023 21:04:11 GMT
    DEBUG: > server: uvicorn
    INFO: connection open
    DEBUG: = connection is OPEN
    DEBUG: = connection is CLOSED
    DEBUG: ! failing connection with code 1006
    DEBUG: x half-closing TCP connection
    INFO: connection closed


    Whats wrong here and how to fix it? I understand that WebsocketConnection was expected, but got HttpResponse, but anyway..

    Continue reading...

Compartilhe esta Página