Simple WebSocket
simple-websocket is a Python library offering a collection of WebSocket servers and clients, supporting both traditional (synchronous) and asynchronous (asyncio) workflows. It simplifies WebSocket communication for standalone applications and integration into larger web frameworks like Flask or ASGI. The project is actively maintained with regular releases, with the latest being 1.1.0.
Warnings
- breaking Version 1.0.0 introduced significant changes. Review the CHANGES.md file on the GitHub repository when upgrading from pre-1.0.0 versions to avoid compatibility issues.
- gotcha When developing WebSocket servers, it is crucial to handle the `ConnectionClosed` exception gracefully. This exception is raised when a client disconnects, allowing your server logic to clean up resources or stop processing for that specific client.
- gotcha For production deployments, always use secure WebSocket connections (`wss://`) instead of insecure ones (`ws://`). Browsers, proxies, and firewalls often block or restrict `ws://` connections, leading to connection failures or security vulnerabilities.
- gotcha If your WebSocket server is behind a reverse proxy (e.g., Nginx, Apache), the proxy must be explicitly configured to correctly handle the WebSocket upgrade headers (`Upgrade` and `Connection`). Misconfiguration will prevent WebSocket connections from establishing.
- gotcha The WebSocket protocol itself does not provide inherent mechanisms for authentication or authorization. Application-level security (e.g., tokens, sessions, origin validation) must be implemented separately to secure your WebSocket connections and data.
Install
-
pip install simple-websocket
Imports
- Server
from simple_websocket import Server
- AioServer
from simple_websocket import AioServer
- Client
from simple_websocket import Client
- AioClient
from simple_websocket import AioClient
- ConnectionClosed
from simple_websocket import ConnectionClosed
- websockets (another library)
from simple_websocket import Client
Quickstart
import time
import threading
from simple_websocket import Client, Server, ConnectionClosed
def run_server():
print("Starting synchronous WebSocket echo server on ws://localhost:8765")
server = Server('ws://localhost:8765')
while True:
try:
print("Server: Waiting for connection...")
client_ws = server.accept()
print("Server: Client connected!")
while True:
try:
message = client_ws.receive()
print(f"Server received: {message}")
client_ws.send(f"Echo: {message}")
except ConnectionClosed:
print("Server: Client disconnected.")
break
except ConnectionClosed:
print("Server: Server closed or error.")
break
def run_client():
print("Starting synchronous WebSocket client...")
time.sleep(1) # Give server time to start
try:
client = Client('ws://localhost:8765')
print("Client connected!")
for i in range(3):
message = f"Hello from client {i+1}"
print(f"Client sending: {message}")
client.send(message)
response = client.receive()
print(f"Client received: {response}")
time.sleep(0.5)
client.close()
print("Client disconnected.")
except ConnectionClosed:
print("Client: Connection closed prematurely.")
except Exception as e:
print(f"Client error: {e}")
if __name__ == '__main__':
server_thread = threading.Thread(target=run_server)
server_thread.daemon = True # Allows main program to exit even if thread is running
server_thread.start()
run_client()
print("Main program finished.")