Registry / http-networking / simple-websocket

simple-websocket

JSON →
library1.1.0pypypi✓ verified 25d ago

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.

pip install simple-websocket
INSTALL
IMPORT
SIG · SIMPLE-WEBSOCKET
S
simple-websocket
http-networkingpythonv1.1.0
Install
1.6s avg
Import
291ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.1.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.310s · 18.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.272s · 19MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Server
from simple_websocket import Server
For creating a synchronous WebSocket server.
AioServer
from simple_websocket import AioServer
For creating an asynchronous WebSocket server (asyncio).
Client
from simple_websocket import Client
For creating a synchronous WebSocket client.
AioClient
from simple_websocket import AioClient
For creating an asynchronous WebSocket client (asyncio).
ConnectionClosed
from simple_websocket import ConnectionClosed
Exception raised when a WebSocket connection is closed, useful for graceful handling.
websockets (another library)
from simple_websocket import Client
import websockets
Avoid confusion with the `websockets` library, which is a different package with a similar purpose but a distinct API.

This example demonstrates a basic synchronous WebSocket echo server and client. The server listens for connections, echoes received messages, and handles client disconnections. The client connects, sends a few messages, receives echoes, and then disconnects.

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.")
Debug
Known issues
breakingVersion 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.
fix
Consult the official 'CHANGES.md' on GitHub for detailed migration steps. Adapt your code to the new API if necessary.
affects: <1.0.0 to 1.0.0+
gotchaWhen 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.
fix
Wrap WebSocket communication (e.g., `receive()`, `send()`) in a `try...except ConnectionClosed:` block and implement appropriate cleanup logic.
affects: All versions
gotchaFor 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.
fix
Ensure your server is configured for WSS (WebSocket Secure) with a valid SSL/TLS certificate, and clients connect using `wss://`.
affects: All versions
gotchaIf 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.
fix
Refer to your proxy server's documentation for WebSocket configuration. For Nginx, this typically involves `proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";`
affects: All versions
gotchaThe 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.
fix
Implement robust authentication and authorization checks at the application layer, potentially during the initial HTTP handshake and for subsequent messages.
affects: All versions
gotchaThe `simple_websocket.Server` class expects a WSGI `environ` dictionary (or ASGI `scope`) as its first argument, not a URL string. Attempting to instantiate it with a URL (e.g., `Server('ws://...')`) will result in an `AttributeError: 'str' object has no attribute 'get'` because the URL string is incorrectly interpreted as the `environ` dictionary.
fix
If you are building a WebSocket server, ensure `simple_websocket.Server` is instantiated with the `environ` (or `scope`) dictionary provided by your WSGI/ASGI server framework. If you intend to connect to an *existing* WebSocket server, use `simple_websocket.Client` (e.g., `client = simple_websocket.Client('ws://localhost:8765')`).
affects: All versions
breakingInitializing `simple_websocket.Server` with a URL can lead to an `AttributeError: 'str' object has no attribute 'get'`. This error indicates that an internal `environ` variable, which the library expects to be a dictionary-like object (e.g., `os.environ`), is incorrectly being treated or set as a string, leading to a failure when attempting to call `.get()` on it.
fix
This appears to be an internal library issue where the `environ` variable gets corrupted or misassigned. Verify you are using the latest stable version of `simple-websocket`. If the error persists, report it to the library maintainers, including the exact Python version, the library version, and the server initialization code (`server = Server('ws://localhost:8765')`).
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'simple_websocket'
The 'simple-websocket' library is not installed in the current Python environment or is not accessible.
fix
Run `pip install simple-websocket` to install the package.
ConnectionRefusedError: [Errno 111] Connection refused
The WebSocket server is not running, is not accessible at the specified address/port, or a firewall is blocking the connection.
fix
Ensure the server is running and listening on the correct host and port (e.g., `ws://127.0.0.1:8000`), and check firewall rules.
AttributeError: 'WebSocketClient' object has no attribute 'send'
The `send` method is on the established WebSocket connection object, not directly on the `WebSocketClient` or `WebSocketServer` instance.
fix
Access the `send` method via the connection object (e.g., `client.connection.send('message')` for a client, or `connection.send('message')` within the server's listener loop).
simple_websocket.WebSocketProtocolError: Incomplete handshake
The client received an invalid WebSocket handshake response, indicating the server might not be a WebSocket server or the handshake failed.
fix
Verify the client is connecting to a correctly configured WebSocket server endpoint, not a standard HTTP endpoint or an incorrectly configured server.
Upgrade
Version history
1.1.0latest on PyPI · released Oct 10, 2024
Audit
Dependencies
PythonrequiredRequires Python 3.6 or newer for execution.
Agent activity
17 hits · last 30 days
node
14
OpenAI (training)
1
Resources