[Python] Which class accurately represents a WebSocket connection?

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have come across multiple ways to describe a websocket connection object while using the websockets library in python but can't seem to understand which way to go.

    In the documentation, the code to start a server is very simple.

    import asyncio

    from websockets.asyncio.server import serve

    async def hello(websocket):
    name = await websocket.recv()
    print(f"<<< {name}")

    greeting = f"Hello {name}!"

    await websocket.send(greeting)
    print(f">>> {greeting}")

    async def main():
    async with serve(hello, "localhost", 8765) as server:
    await server.serve_forever()

    if __name__ == "__main__":
    asyncio.run(main())


    But when I simply copy and paste the code, the IDE cannot recognize the .recv() and the .send() methods. So I started to look around what is the type of the websocket object to get some idea about it and what other methods are available for that object. So I found that all these can be used:

    - websockets.ServerConnection
    - websockets.server.ServerConnection
    - websockets.asyncio.server.ServerConnection


    I think the methods they provide are the same. If these are significantly different, then an explanation? Can I use any of the three and it won't make much difference?

    In the documentation, the asyncio implementation of the server creates a websockets.asyncio.server.ServerConnection instance upon client connection. So then what are the other classes?

    I'm sorry if this is too basic.

    Continue reading...

Compartilhe esta Página