1 min read

Python Websockets Library

websockets is a library for building WebSocket servers and clients in Python. It is built on top of asyncio.

Installation

pip install websockets

Server Implementation

Here is a simple echo server that replies to messages.

import asyncio
import websockets

async def echo(websocket):
    async for message in websocket:
        await websocket.send(message)

async def main():
    async with websockets.serve(echo, "localhost", 8765):
        await asyncio.get_running_loop().create_future()  # Run forever

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

Client Implementation

Here is a client that connects to the server, sends a message, and prints the response.

import asyncio
import websockets

async def hello():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello world!")
        response = await websocket.recv()
        print(f"Received: {response}")

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

Secure WebSockets (WSS)

To enable SSL/TLS (wss://), you need to pass an ssl_context to the server or client.

import ssl
import websockets

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain(certfile="cert.pem", keyfile="key.pem")

# In main():
# async with websockets.serve(echo, "localhost", 8765, ssl=ssl_context):

programming/python/python