python-websocket-server

repository·master·Indexed 22 days ago

https://github.com/pithikos/python-websocket-server

A minimal, dependency-free WebSocket server for Python 3.6+ designed for prototyping, testing, or providing a communication layer for GUI applications. It features the WebsocketServer class for managing connections, SSL support, and a callback system for handling new clients, disconnections, and received messages.

Tokens
1.7K
Snippets
9
Records
11
Agent score
29%

What's inside python-websocket-server

  1. Understand the Client object structure

    master

    In this library, a client is represented as a dictionary containing the following keys:

    {
    	'id'      : client_id,
    	'handler' : client_handler,
    	'address' : (addr, port)
    }

    This dictionary is passed to all callback functions and is required when using send_message(client, message) to target a specific user.

    {
    	'id'      : client_id,
    	'handler' : client_handler,
    	'address' : (addr, port)
    }
  2. Configure WebsocketServer callbacks

    master

    You can define custom logic for server events by setting callback functions using the following methods. All callbacks receive the client and the server instance as arguments.

    Event Callbacks

    MethodEventCallback Parameters
    set_fn_new_client(fn)A new client connectsclient, server
    set_fn_client_left(fn)A client disconnectsclient, server
    set_fn_message_received(fn)A client sends a messageclient, server, message

    Example: Handling new clients and messages

    import logging
    from websocket_server import WebsocketServer
    
    def on_new_client(client, server):
        server.send_message_to_all("A new client has joined!")
    
    def on_message(client, server, message):
        print(f"Received: {message}")
        server.send_message(client, "Message received")
    
    server = WebsocketServer(host='127.0.0.1', port=13254, loglevel=logging.INFO)
    server.set_fn_new_client(on_new_client)
    server.set_fn_message_received(on_message)
    server.run_forever()
    import logging
    from websocket_server import WebsocketServer
    
    def new_client(client, server):
    	server.send_message_to_all("Hey all, a new client has joined us")
    
    server = WebsocketServer(host='127.0.0.1', port=13254, loglevel=logging.INFO)
    server.set_fn_new_client(new_client)
    server.run_forever()
  3. Manage server lifecycle and connections

    master

    Use these methods to control the server execution and connection state:

    Server Execution

    • run_forever(threaded=False): Starts the server. If threaded is True, the server runs in its own thread.
    • shutdown_gracefully(status, reason): Disconnects clients with a CLOSE handshake and shuts down the server.
    • shutdown_abruptly(): Disconnects clients and shuts down the server immediately without a handshake.

    Connection Control

    • deny_new_connections(status, reason): Closes connections for any new clients attempting to connect.
    • allow_new_connections(): Re-enables connections for new clients.
    • disconnect_clients_gracefully(status, reason): Sends a websocket CLOSE handshake to all connected clients.
    • disconnect_clients_abruptly(): Disconnects all clients immediately (clients only notice upon next data attempt).
  4. Initialize the WebsocketServer class

    master

    The WebsocketServer class is the main entry point. You can configure the server using the following parameters during initialization:

    • port: The port clients will connect to.
    • host: The hostname. Defaults to 127.0.0.1 (local connections only). Use 0.0.0.0 to allow connections from any network machine.
    • loglevel: The logging level (e.g., logging.DEBUG, logging.INFO, logging.WARNING). Defaults to WARNING.
    • key: (SSL only) Path to the SSL key file.
    • cert: (SSL only) Path to the SSL certificate file.
    from websocket_server import WebsocketServer
    import logging
    
    server = WebsocketServer(host='0.0.0.0', port=13254, loglevel=logging.INFO)
  5. Initialize and run a WebsocketServer

    master

    To start a websocket server, instantiate the WebsocketServer class with a port argument. You can then use run_forever() to start the server loop, which will keep the process running and listening for connections.

    from websocket_server import WebsocketServer
    
    PORT = 9001
    server = WebsocketServer(port=PORT)
    server.run_forever()
  6. Handle incoming messages with set_fn_message_received

    master

    Register a callback function using set_fn_message_received(callback) to process messages sent by clients.

    Callback Signature: callback(client, server, message)

    • client: A dictionary containing client information (e.g., client['id']).
    • server: The WebsocketServer instance.
    • message: The string content of the received message.
    def message_received(client, server, message):
        print("Client(%d) said: %s" % (client['id'], message))
    
    server.set_fn_message_received(message_received)
  7. Handle new client connections with set_fn_new_client

    master

    Register a callback function using set_fn_new_client(callback) to execute logic whenever a new client successfully completes a handshake.

    Callback Signature: callback(client, server)

    • client: A dictionary containing client information (e.g., client['id']).
    • server: The WebsocketServer instance.
    def new_client(client, server):
        print("New client connected and was given id %d" % client['id'])
    
    server.set_fn_new_client(new_client)
  8. Handle client disconnections with set_fn_client_left

    master

    Register a callback function using set_fn_client_left(callback) to execute logic when a client disconnects from the server.

    Callback Signature: callback(client, server)

    • client: A dictionary containing client information (e.g., client['id']).
    • server: The WebsocketServer instance.
    def client_left(client, server):
        print("Client(%d) disconnected" % client['id'])
    
    server.set_fn_client_left(client_left)