websockets
An implementation of the WebSocket Protocol (RFC 6455 & 7692) for Python, currently at version 16.0, with a release cadence of approximately every 6 months.
Warnings
- breaking websockets 16.0 requires Python ≥ 3.10; 15.0 is the last version supporting Python 3.9.
- breaking Receiving the request path in the second parameter of connection handlers is deprecated; use 'path = request.path' inside the handler function.
- gotcha Ensure correct import paths to avoid 'NameError' when importing 'serve' or 'connect'.
Install
-
pip install websockets
Imports
- serve
from websockets import serve
- connect
from websockets import connect
Quickstart
import asyncio
from websockets import serve
async def handler(websocket, path):
async for message in websocket:
await websocket.send(f'Hello, {message}!')
async def main():
async with serve(handler, 'localhost', 8765):
await asyncio.Future() # Run forever
if __name__ == '__main__':
asyncio.run(main())