### Run the example server Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Execute the default server script to start the websocket server. This is useful for a quick demonstration or to test client connectivity. ```bash python server.py ``` -------------------------------- ### Full Echo-Chat Server Example Source: https://context7.com/pithikos/python-websocket-server/llms.txt A comprehensive example demonstrating how to set up a websocket server with callbacks for new clients, client disconnections, and message handling. It includes broadcasting messages to all clients and sending targeted replies. ```python import logging from websocket_server import WebsocketServer def new_client(client, server): print(f"New client #{client['id']} from {client['address']}") server.send_message_to_all(f"[Server] Client #{client['id']} joined. Online: {len(server.clients)}") def client_left(client, server): print(f"Client #{client['id']} left") server.send_message_to_all(f"[Server] Client #{client['id']} left. Online: {len(server.clients)}") def message_received(client, server, message): if len(message) > 200: message = message[:200] + ".." print(f"Client #{client['id']} said: {message}") # Broadcast to everyone else for c in server.clients: if c['id'] != client['id']: server.send_message(c, f"[#{client['id']}] {message}") else: server.send_message(c, f"[You] {message}") server = WebsocketServer(host='0.0.0.0', port=9001, loglevel=logging.INFO) server.set_fn_new_client(new_client) server.set_fn_client_left(client_left) server.set_fn_message_received(message_received) server.run_forever() ``` -------------------------------- ### Install websocket-server with pip Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Install the websocket-server package using pip. This command is used to add the library to your Python environment. ```bash pip install websocket-server ``` -------------------------------- ### Start Server in Background Source: https://context7.com/pithikos/python-websocket-server/llms.txt Use `run_forever(threaded=True)` to start the server in a separate daemon thread, allowing the main thread to continue execution. Remember to call `shutdown_gracefully()` when done. ```python import time from websocket_server import WebsocketServer server = WebsocketServer(host='127.0.0.1', port=9001) # Non-blocking: server runs in background server.run_forever(threaded=True) print(f"Server running on port {server.port}") # Do other work while the server accepts connections time.sleep(30) server.shutdown_gracefully() ``` -------------------------------- ### Set New Client Callback Function with SSL Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md This example demonstrates setting a callback for new clients when using SSL encryption. You must provide paths to your SSL key and certificate files. ```python 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, key="key.pem", cert="cert.pem") server.set_fn_new_client(new_client) server.run_forever() ``` -------------------------------- ### run_forever Source: https://context7.com/pithikos/python-websocket-server/llms.txt Starts the server event loop. It can either block the calling thread or run in a separate daemon thread. ```APIDOC ## `run_forever(threaded=False)` — Start the server Starts the server event loop. When `threaded=False` (default) it blocks the calling thread. When `threaded=True` it starts the server on a daemon `WebsocketServerThread` and returns immediately, allowing the main thread to continue. ### Parameters - **threaded** (bool) - Optional - If True, runs the server in a background daemon thread. ``` -------------------------------- ### Run all tests with pytest Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Execute all the project's tests using the pytest framework. Ensure you have pytest installed to run this command. ```bash pytest ``` -------------------------------- ### Run the server in a separate thread Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Start the websocket server in its own thread, allowing the main program to continue execution. This is useful for non-blocking server operations. ```python server.run_forever(threaded=True) ``` -------------------------------- ### Initialize WebsocketServer with custom host and port Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Demonstrates initializing the WebsocketServer. You can specify the port and host. Use '0.0.0.0' for the host to allow connections from any network machine. ```python server = WebsocketServer(port=8000, host='0.0.0.0') ``` -------------------------------- ### Initialize and Connect WebSocket Client Source: https://github.com/pithikos/python-websocket-server/blob/master/client.html Establishes a WebSocket connection and sets up event handlers for open, message, close, and error events. Ensure the server is running at ws://localhost:9001/. ```javascript var ws; function init() { // Connect to Web Socket ws = new WebSocket("ws://localhost:9001/"); // Set event handlers. ws.onopen = function() { output("onopen"); }; ws.onmessage = function(e) { // e.data contains received string. output("onmessage: " + e.data); }; ws.onclose = function() { output("onclose"); }; ws.onerror = function(e) { output("onerror"); console.log(e) }; } ``` -------------------------------- ### Create WebsocketServer Instance Source: https://context7.com/pithikos/python-websocket-server/llms.txt Instantiate a WebsocketServer, specifying host, port, and logging level. SSL can be enabled by providing paths to key and certificate files. ```python import logging from websocket_server import WebsocketServer # Plain server accessible only from localhost server = WebsocketServer(host='127.0.0.1', port=9001, loglevel=logging.INFO) # Server accessible from any host with SSL enabled ssl_server = WebsocketServer( host='0.0.0.0', port=9443, loglevel=logging.WARNING, key='server.key.pem', cert='server.cert.pem', ) ``` -------------------------------- ### WebsocketServer Initialization Source: https://context7.com/pithikos/python-websocket-server/llms.txt Instantiates a WebSocket server bound to the given host and port. SSL can be enabled by providing paths to a PEM key and certificate. ```APIDOC ## WebsocketServer(host, port, loglevel, key, cert) ### Description Instantiates a WebSocket server bound to the given host and port. By default the server only accepts connections from `127.0.0.1`; pass `host='0.0.0.0'` to accept connections from any network interface. SSL is enabled by supplying paths to a PEM key and certificate. ### Parameters - **host** (string) - The host address to bind the server to. Defaults to '127.0.0.1'. - **port** (int) - The port number to listen on. - **loglevel** (int) - The logging level (e.g., `logging.INFO`). - **key** (string, optional) - Path to the SSL private key file. - **cert** (string, optional) - Path to the SSL certificate file. ### Request Example ```python import logging from websocket_server import WebsocketServer # Plain server accessible only from localhost server = WebsocketServer(host='127.0.0.1', port=9001, loglevel=logging.INFO) # Server accessible from any host with SSL enabled ssl_server = WebsocketServer( host='0.0.0.0', port=9443, loglevel=logging.WARNING, key='server.key.pem', cert='server.cert.pem', ) ``` ``` -------------------------------- ### WebsocketServer Initialization Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md The WebsocketServer can be initialized with several parameters to configure its behavior, including port, host, logging level, and SSL certificates. ```APIDOC ## WebsocketServer The WebsocketServer can be initialized with the below parameters. *`port`* - The port clients will need to connect to. *`host`* - By default the `127.0.0.1` is used which allows connections only from the current machine. If you wish to allow all network machines to connect, you need to pass `0.0.0.0` as hostname. *`loglevel`* - logging level to print. By default WARNING is used. You can use `logging.DEBUG` or `logging.INFO` for more verbose output. *`key`* - If using SSL, this is the path to the key. *`cert`* - If using SSL, this is the path to the certificate. ``` -------------------------------- ### Allow new incoming connections Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Re-enable the ability for new clients to connect to the server after it might have been denied. ```python server.allow_new_connections() ``` -------------------------------- ### Register New Client Callback Source: https://context7.com/pithikos/python-websocket-server/llms.txt Set a callback function to be executed when a new client connects and completes the WebSocket handshake. The callback receives the client dictionary and server instance. ```python from websocket_server import WebsocketServer def on_new_client(client, server): # client dict: {'id': int, 'handler': handler, 'address': (ip, port)} print(f"Client #{client['id']} connected from {client['address'][0]}") server.send_message_to_all(f"User {client['id']} has joined!") server = WebsocketServer(host='127.0.0.1', port=9001) server.set_fn_new_client(on_new_client) server.run_forever() ``` -------------------------------- ### set_fn_new_client(fn) Source: https://context7.com/pithikos/python-websocket-server/llms.txt Registers a callback function that is called whenever a new client successfully completes the WebSocket handshake and connects to the server. ```APIDOC ## set_fn_new_client(fn) ### Description Sets the function called whenever a client completes the WebSocket handshake and joins. The callback receives the `client` dict and the `server` instance. ### Parameters - **fn** (function) - The callback function to register. It accepts two arguments: `client` (dict) and `server` (WebsocketServer instance). ### Request Example ```python from websocket_server import WebsocketServer def on_new_client(client, server): # client dict: {'id': int, 'handler': handler, 'address': (ip, port)} print(f"Client #{client['id']} connected from {client['address'][0]}") server.send_message_to_all(f"User {client['id']} has joined!") server = WebsocketServer(host='127.0.0.1', port=9001) server.set_fn_new_client(on_new_client) server.run_forever() ``` ``` -------------------------------- ### shutdown_gracefully / shutdown_abruptly Source: https://context7.com/pithikos/python-websocket-server/llms.txt Stops the server. `shutdown_gracefully` closes connections with a handshake, while `shutdown_abruptly` terminates them immediately. ```APIDOC ## `shutdown_gracefully(status, reason)` / `shutdown_abruptly()` — Stop the server `shutdown_gracefully()` sends a WebSocket CLOSE frame (with optional RFC 6455 status code and reason bytes) to every client before closing the server socket. `shutdown_abruptly()` terminates all connections immediately without a handshake. ### Parameters for `shutdown_gracefully` - **status** (int) - Optional - RFC 6455 status code. - **reason** (bytes) - Optional - Reason for closing the connection. ``` -------------------------------- ### Set New Client Callback Function Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Use this to define a function that will be called every time a new client connects to the server. Ensure the `websocket_server` library is imported. ```python 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() ``` -------------------------------- ### server.clients Source: https://context7.com/pithikos/python-websocket-server/llms.txt Provides access to a list of all currently connected clients, with details for each client. ```APIDOC ## `server.clients` — Inspect connected clients A list of `client` dicts for all currently connected clients. Each entry contains `id` (int), `handler`, and `address` (tuple of IP string and port int). ``` -------------------------------- ### Set callback for new client connections Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Assign a function to be called whenever a new client connects to the server. The connected client object is passed to the callback function. ```python server.set_fn_new_client(new_client_connected) ``` -------------------------------- ### Client Dictionary Structure Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md A client is represented as a dictionary containing its ID, handler, and network address. This structure is passed to various callback functions. ```python { 'id' : client_id, 'handler' : client_handler, 'address' : (addr, port) } ``` -------------------------------- ### deny_new_connections / allow_new_connections Source: https://context7.com/pithikos/python-websocket-server/llms.txt Controls the acceptance of new client connections. `deny_new_connections` temporarily blocks new clients, while `allow_new_connections` re-enables them. ```APIDOC ## `deny_new_connections(status, reason)` / `allow_new_connections()` — Gate new connections Temporarily prevents new clients from establishing a connection (useful during maintenance windows) while keeping existing clients connected. `allow_new_connections()` lifts the restriction. ### Parameters for `deny_new_connections` - **status** (int) - Optional - RFC 6455 status code. - **reason** (bytes) - Optional - Reason for denying new connections. ``` -------------------------------- ### Send a message to all connected clients Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Broadcast a string message to all clients currently connected to the server. ```python server.send_message_to_all("Broadcasting message to all clients!") ``` -------------------------------- ### WebsocketServer Methods Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md A collection of methods for managing the websocket server, handling client connections, sending messages, and controlling server lifecycle. ```APIDOC ### Methods | Method | |-----------------------------| | `run_forever()` | Runs server until shutdown_gracefully or shutdown_abruptly are called. | | `set_fn_new_client()` | Sets a callback function that will be called for every new `client` connecting to us | | `set_fn_client_left()` | Sets a callback function that will be called for every `client` disconnecting from us | | `set_fn_message_received()` | Sets a callback function that will be called when a `client` sends a message | | `send_message()` | Sends a `message` to a specific `client`. The message is a simple string. | | `send_message_to_all()` | Sends a `message` to **all** connected clients. The message is a simple string. | | `disconnect_clients_gracefully()` | Disconnect all connected clients by sending a websocket CLOSE handshake. | | `disconnect_clients_abruptly()` | Disconnect all connected clients. Clients won't be aware until they try to send some data. | | `shutdown_gracefully()` | Disconnect clients with a CLOSE handshake and shutdown server. | | `shutdown_abruptly()` | Disconnect clients and shutdown server with no handshake. | | `deny_new_connections()` | Close connection for new clients. | | `allow_new_connections()` | Allows back connection for new clients. | ``` -------------------------------- ### Abruptly shut down the server Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Immediately disconnect all clients and terminate the server process without any handshake. ```python server.shutdown_abruptly() ``` -------------------------------- ### Gracefully disconnect all clients Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Initiate a graceful shutdown by sending a websocket CLOSE handshake to all connected clients. Optional status code and reason can be provided. ```python server.disconnect_clients_gracefully(status=1000, reason="Server shutting down") ``` -------------------------------- ### Inspect Connected Clients Source: https://context7.com/pithikos/python-websocket-server/llms.txt Access the `server.clients` list to view details of connected clients, including their `id`, `handler`, and `address`. This can be used to send targeted messages or monitor connections. ```python from websocket_server import WebsocketServer def on_new_client(client, server): ids = [c['id'] for c in server.clients] addrs = [c['address'][0] for c in server.clients] print(f"Connected client IDs: {ids}") print(f"Connected addresses : {addrs}") server.send_message(client, f"You are client #{client['id']}. Total online: {len(server.clients)}") server = WebsocketServer(host='127.0.0.1', port=9001) server.set_fn_new_client(on_new_client) server.run_forever() ``` -------------------------------- ### Send a message to a specific client Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Send a string message to an individual client. Requires the client object and the message content. ```python server.send_message(client, "Hello from server!") ``` -------------------------------- ### Register Message Reception Callback Source: https://context7.com/pithikos/python-websocket-server/llms.txt Specify a callback function to handle incoming text messages from clients. The callback receives the client dictionary, server instance, and the decoded message string. ```python from websocket_server import WebsocketServer def on_message(client, server, message): print(f"Client #{client['id']} said: {message}") # Echo the message back to the sender only server.send_message(client, f"Echo: {message}") server = WebsocketServer(host='127.0.0.1', port=9001) server.set_fn_message_received(on_message) server.run_forever() ``` -------------------------------- ### Broadcast Message to All Clients Source: https://context7.com/pithikos/python-websocket-server/llms.txt Employ `send_message_to_all` to broadcast a UTF-8 text message to all currently connected clients. This method is thread-safe. ```python import threading from websocket_server import WebsocketServer server = WebsocketServer(host='127.0.0.1', port=9001) server.run_forever(threaded=True) # run in background # Broadcast a ticker update every 5 seconds from the main thread def broadcast_tick(n=0): server.send_message_to_all(f"Tick #{n}") threading.Timer(5.0, broadcast_tick, args=[n + 1]).start() broadcast_tick() ``` -------------------------------- ### Disconnect All Clients Gracefully Source: https://context7.com/pithikos/python-websocket-server/llms.txt Use `disconnect_clients_gracefully()` to disconnect all clients with a close frame, or `disconnect_clients_abruptly()` for immediate termination. The server remains active to accept new connections. ```python from websocket_server import WebsocketServer def on_message(client, server, message): if message == "/kick-all": # Politely disconnect everyone server.disconnect_clients_gracefully(status=1000, reason=b"Session reset") print("All clients disconnected; server still running.") server = WebsocketServer(host='127.0.0.1', port=9001) server.set_fn_message_received(on_message) server.run_forever() ``` -------------------------------- ### WebsocketServer Properties Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md The WebsocketServer class exposes a 'clients' property which is a list of all currently connected client objects. ```APIDOC ### Properties | Property | |----------|----------| | clients | A list of `client` | ``` -------------------------------- ### set_fn_client_left(fn) Source: https://context7.com/pithikos/python-websocket-server/llms.txt Registers a callback function that is executed when a client disconnects from the server, either gracefully or due to a network error. ```APIDOC ## set_fn_client_left(fn) ### Description Sets the function called whenever a client disconnects (either gracefully or due to a network error). The callback receives the `client` dict of the departing client and the `server`. ### Parameters - **fn** (function) - The callback function to register. It accepts two arguments: `client` (dict) and `server` (WebsocketServer instance). ### Request Example ```python from websocket_server import WebsocketServer connected_users = {} def on_client_left(client, server): name = connected_users.pop(client['id'], f"Client #{client['id']}") print(f"{name} disconnected") server.send_message_to_all(f"{name} has left the chat.") server = WebsocketServer(host='127.0.0.1', port=9001) server.set_fn_client_left(on_client_left) server.run_forever() ``` ``` -------------------------------- ### Gracefully shut down the server Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Disconnect all clients with a CLOSE handshake and then shut down the server process. Optional status code and reason can be provided for client disconnection. ```python server.shutdown_gracefully(status=1000, reason="Server maintenance") ``` -------------------------------- ### Deny New Connections Temporarily Source: https://context7.com/pithikos/python-websocket-server/llms.txt Call `deny_new_connections()` to block incoming connections while keeping existing ones active. Use `allow_new_connections()` to re-enable new client connections. This is useful for maintenance. ```python import time from websocket_server import WebsocketServer server = WebsocketServer(host='127.0.0.1', port=9001) server.run_forever(threaded=True) # Maintenance window: block new connections for 10 seconds server.deny_new_connections(status=1013, reason=b"Maintenance in progress") print("New connections are now denied.") time.sleep(10) server.allow_new_connections() print("New connections are allowed again.") ``` -------------------------------- ### Deny new incoming connections Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Prevent any new clients from connecting to the server. Existing connections remain active. Optional status code and reason can be provided. ```python server.deny_new_connections(status=1001, reason="Server is busy") ``` -------------------------------- ### disconnect_clients_gracefully / disconnect_clients_abruptly Source: https://context7.com/pithikos/python-websocket-server/llms.txt Disconnects all currently connected clients without stopping the server, allowing new connections to be established. ```APIDOC ## `disconnect_clients_gracefully(status, reason)` / `disconnect_clients_abruptly()` — Kick all clients Disconnects every connected client without stopping the server itself, so new connections can still be accepted afterwards. ### Parameters for `disconnect_clients_gracefully` - **status** (int) - Optional - RFC 6455 status code. - **reason** (bytes) - Optional - Reason for disconnecting clients. ``` -------------------------------- ### Register Client Disconnection Callback Source: https://context7.com/pithikos/python-websocket-server/llms.txt Define a callback function that is invoked when a client disconnects. This function receives the client dictionary of the departing client and the server instance. ```python from websocket_server import WebsocketServer connected_users = {} def on_client_left(client, server): name = connected_users.pop(client['id'], f"Client #{client['id']}") print(f"{name} disconnected") server.send_message_to_all(f"{name} has left the chat.") server = WebsocketServer(host='127.0.0.1', port=9001) server.set_fn_client_left(on_client_left) server.run_forever() ``` -------------------------------- ### send_message_to_all(message) Source: https://context7.com/pithikos/python-websocket-server/llms.txt Broadcasts a UTF-8 text message to all currently connected clients. This operation is thread-safe. ```APIDOC ## send_message_to_all(message) ### Description Sends a UTF-8 text message to every currently connected client. Thread-safe. ### Parameters - **message** (string) - The UTF-8 text message to broadcast. ### Request Example ```python import threading from websocket_server import WebsocketServer server = WebsocketServer(host='127.0.0.1', port=9001) server.run_forever(threaded=True) # run in background # Broadcast a ticker update every 5 seconds from the main thread def broadcast_tick(n=0): server.send_message_to_all(f"Tick #{n}") threading.Timer(5.0, broadcast_tick, args=[n + 1]).start() broadcast_tick() ``` ``` -------------------------------- ### Gracefully Stop Server Source: https://context7.com/pithikos/python-websocket-server/llms.txt Call `shutdown_gracefully()` to send a close frame to all clients before stopping the server. For immediate termination without a handshake, use `shutdown_abruptly()`. ```python import time, threading from websocket_server import WebsocketServer server = WebsocketServer(host='127.0.0.1', port=9001) server.run_forever(threaded=True) # Graceful shutdown after 60 seconds time.sleep(60) server.shutdown_gracefully(status=1001, reason=b"Server going offline") # --- Or, for immediate shutdown: --- # server.shutdown_abruptly() ``` -------------------------------- ### Set callback for received messages Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Define a function to handle incoming messages from clients. The client and the message content are provided to the callback. ```python server.set_fn_message_received(message_received) ``` -------------------------------- ### Abruptly disconnect all clients Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Immediately disconnect all clients without a proper websocket handshake. Clients will only notice upon their next communication attempt. ```python server.disconnect_clients_abruptly() ``` -------------------------------- ### Set callback for client disconnections Source: https://github.com/pithikos/python-websocket-server/blob/master/README.md Assign a function to be called when a client disconnects. The client object that left is passed to the callback function. ```python server.set_fn_client_left(client_disconnected) ``` -------------------------------- ### Send Message to a Single Client Source: https://context7.com/pithikos/python-websocket-server/llms.txt Use the `send_message` method to transmit a UTF-8 text message to a specific connected client, identified by its client dictionary. ```python from websocket_server import WebsocketServer def on_message(client, server, message): if message.startswith("/hello"): server.send_message(client, "Hello to you too!") else: server.send_message(client, f"You said: {message}") server = WebsocketServer(host='127.0.0.1', port=9001) server.set_fn_message_received(on_message) server.run_forever() ``` -------------------------------- ### send_message(client, message) Source: https://context7.com/pithikos/python-websocket-server/llms.txt Sends a UTF-8 text message to a specific connected client. ```APIDOC ## send_message(client, message) ### Description Sends a UTF-8 text message to a single connected client identified by its `client` dict. ### Parameters - **client** (dict) - The dictionary representing the client to send the message to. - **message** (string) - The UTF-8 text message to send. ### Request Example ```python from websocket_server import WebsocketServer def on_message(client, server, message): if message.startswith("/hello"): server.send_message(client, "Hello to you too!") else: server.send_message(client, f"You said: {message}") server = WebsocketServer(host='127.0.0.1', port=9001) server.set_fn_message_received(on_message) server.run_forever() ``` ``` -------------------------------- ### Send Message via WebSocket Source: https://github.com/pithikos/python-websocket-server/blob/master/client.html Sends a message from an input field to the connected WebSocket server. The input field should have the ID 'input'. ```javascript function onSubmit() { var input = document.getElementById("input"); // You can send message to the Web Socket using ws.send. ws.send(input.value); output("send: " + input.value); input.value = ""; input.focus(); } ``` -------------------------------- ### set_fn_message_received(fn) Source: https://context7.com/pithikos/python-websocket-server/llms.txt Registers a callback function that is invoked when the server receives a text message from any connected client. ```APIDOC ## set_fn_message_received(fn) ### Description Sets the function called whenever a text frame is received from a client. The callback receives the `client` dict, the `server`, and the decoded `message` string. ### Parameters - **fn** (function) - The callback function to register. It accepts three arguments: `client` (dict), `server` (WebsocketServer instance), and `message` (string). ### Request Example ```python from websocket_server import WebsocketServer def on_message(client, server, message): print(f"Client #{client['id']} said: {message}") # Echo the message back to the sender only server.send_message(client, f"Echo: {message}") server = WebsocketServer(host='127.0.0.1', port=9001) server.set_fn_message_received(on_message) server.run_forever() ``` ``` -------------------------------- ### Output Messages to Log Source: https://github.com/pithikos/python-websocket-server/blob/master/client.html Appends messages to an HTML element with the ID 'log', escaping HTML special characters to prevent rendering issues. ```javascript function output(str) { var log = document.getElementById("log"); var escaped = str.replace(/&/, "&").replace(//, ">").replace(/"/, """); // " log.innerHTML = escaped + "
" + log.innerHTML; } ``` -------------------------------- ### Close WebSocket Connection Source: https://github.com/pithikos/python-websocket-server/blob/master/client.html Closes the active WebSocket connection. ```javascript function onCloseClick() { ws.close(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.