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.
No need to apologize — your question is valid, and it’s clear you’re trying to understand how the websockets
library works. That’s awesome!
So, here’s what’s going on:
When you define async def hello(websocket)
, the websocket
parameter is the connection object to the client. Specifically, if you’re using websockets.asyncio.server.serve
, that websocket
is an instance of websockets.asyncio.server.ServerConnection
.
The .recv()
and .send()
methods you’re using are part of that class — they’re the standard methods to receive and send messages. If your IDE doesn’t recognize them, it’s probably just not sure what type websocket
is, or it’s missing some type hints.
Now about those different class names:
websockets.ServerConnection
— this is basically a shortcut to one of the actual implementations.
websockets.server.ServerConnection
— this might be from an older version or an intermediate module path.
websockets.asyncio.server.ServerConnection
— this is the one you want to use when working with asyncio. It’s what the serve() function actually creates behind the scenes.