websockets?websockets is a library for building Documentation is available on Read the Docs.
Here's an echo server with the asyncio API:
#!/usr/bin/env python
import asyncio
from websockets.server import serve
async def echo(websocket):
async for message in websocket:
await websocket.send(message)
async def main():
async with serve(echo, "localhost", 8765):
await asyncio.get_running_loop().create_future() # run forever
asyncio.run(main())
Here's how a client sends and receives messages with the threading API:
#!/usr/bin/env python
from websockets.sync.client import connect
def hello():
with connect("ws://localhost:8765") as websocket:
websocket.send("Hello world!")
message = websocket.recv()
print(f"Received: {message}")
hello()
Does that look good?
Available as part of the Tidelift Subscription
The maintainers of websockets and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. let me know.)
websockets?The development of websockets is shaped by four principles:
websockets is heavily tested for compliance with
handle backpressure correctly before the issue
became widely known in the Python community.Documentation is a first class concern in the project. Head over to Why shouldn't I use websockets?
If you prefer callbacks over coroutines: websockets was created to
provide the best coroutine-based API to manage WebSocket connections in
Python. Pick another library for a callback-based API.
If you're looking for a mixed HTTP / WebSocket library: websockets aims
at being an excellent implementation of RFC 7692: Compression Extensions for WebSocket. Its support for HTTP
is minimal — just enough for an HTTP health check.
If you want to do both in the same server, look at HTTP frameworks that
build on top of websockets to support WebSocket connections, like
What else?
Bug reports, patches and suggestions are welcome!
To report a security vulnerability, please use the issue or send a Contributor Covenant code of conduct.
websockets is released under the /source-code-sync/websockets