wslink

2.5.6 · active · verified Tue Apr 14

wslink is a Python/JavaScript library designed for robust communication over WebSockets. It facilitates easy bi-directional communication, supporting Remote Procedure Calls (RPC) from client to server and publish/subscribe patterns from server to client, including binary attachments. Maintained by Kitware, it is actively developed with a frequent release cadence, often driven by semantic versioning.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a basic `wslink` Python server with two Remote Procedure Call (RPC) methods: `my.hello` for greetings and `my.add` for adding numbers. It defines a custom protocol and handler, then uses `run_wslink` to start the server. Clients can connect via WebSocket to `ws://127.0.0.1:8080` and call the exposed methods.

import asyncio
import logging

from wslink import Server
from wslink.websocket import WslinkHandler, run_wslink
from wslink.protocols import WslinkServerProtocol

# Configure logging for better visibility
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class MyProtocol(WslinkServerProtocol):
    """A simple protocol demonstrating RPC."""

    def initialize(self):
        # Register this protocol for RPC calls
        self.registerVtkWebProtocol(self)
        logger.info("MyProtocol initialized.")

    @Server.expose("my.hello")
    def hello_world(self, name="World"):
        """An RPC method that returns a greeting."""
        logger.info(f"RPC 'my.hello' called with name='{name}'.")
        return f"Hello, {name} from wslink!"

    @Server.expose("my.add")
    def add_numbers(self, a, b):
        """An RPC method that adds two numbers."""
        logger.info(f"RPC 'my.add' called with a={a}, b={b}.")
        return a + b

class MyWslinkHandler(WslinkHandler):
    """Custom wslink handler to use our protocol."""
    protocol_class = MyProtocol

async def main():
    # Set the host and port for the WebSocket server
    host = "127.0.0.1"
    port = 8080

    logger.info(f"Starting wslink server on ws://{host}:{port}")
    logger.info("Press Ctrl+C to stop the server.")

    # Run the wslink server
    await run_wslink(
        port=port,
        host=host,
        ws=MyWslinkHandler,
        # Optionally, set a secret for client authentication:
        # secret=os.environ.get('WSLINK_SECRET', 'your_default_secret')
    )

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("Server stopped by user (KeyboardInterrupt).")
    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")

view raw JSON →