Simple WebSocket

1.1.0 · active · verified Sun Apr 05

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

Install

Imports

Quickstart

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.")

view raw JSON →