Skip to content

Getting Started

This guide will get you up and running with PyStrands in minutes.

Installation

Install PyStrands from PyPI:

pip install pystrands

Python Version

PyStrands requires Python 3.10 or higher.

Running the Server

PyStrands includes a Go-based broker that handles WebSocket connections. The server binary is automatically downloaded for your platform on first run.

Basic Usage

python -m pystrands server

This starts the server with default settings: - WebSocket port: 8080 (for browser clients) - TCP port: 8081 (for Python backends) - Queue size: 1000 (message buffer)

Command Options

python -m pystrands server --ws-port 8080 --tcp-port 8081 --queue-size 1000
Option Description Default
--ws-port WebSocket port for clients 8080
--tcp-port TCP port for Python backends 8081
--queue-size Message buffer when no backends connected (0 = disabled) 1000

Server Binary

The server binary is downloaded to ~/.pystrands/pystrands-server on first run. Subsequent runs use the cached binary unless the version changes.

Creating Your First Backend

The async client is ideal for modern Python applications using asyncio:

import asyncio
from pystrands import AsyncPyStrandsClient

class ChatBackend(AsyncPyStrandsClient):
    async def on_connection_request(self, request):
        """Handle new WebSocket connection requests."""
        # Extract room from URL path
        request.context.room_id = request.url.strip("/")
        return True  # Accept the connection

    async def on_message(self, message, context):
        """Handle messages from clients."""
        print(f"[{context.room_id}] {context.client_id}: {message}")
        # Echo back to the room
        await self.send_room_message(context.room_id, f"echo: {message}")

    async def on_disconnect(self, context):
        """Handle client disconnections."""
        print(f"{context.client_id} left {context.room_id}")

# Create and run the client
client = ChatBackend(host="localhost", port=8081)
asyncio.run(client.run_forever())

Sync Client

For simpler applications or when asyncio isn't needed:

from pystrands import PyStrandsClient

class ChatBackend(PyStrandsClient):
    def on_connection_request(self, request):
        """Handle new WebSocket connection requests."""
        request.context.room_id = request.url.strip("/")
        return True

    def on_message(self, message, context):
        """Handle messages from clients."""
        print(f"[{context.room_id}] {context.client_id}: {message}")
        self.send_room_message(context.room_id, f"echo: {message}")

    def on_disconnect(self, context):
        """Handle client disconnections."""
        print(f"{context.client_id} left {context.room_id}")

# Create and run the client
client = ChatBackend(host="localhost", port=8081)
client.run_forever()

Testing with a WebSocket Client

You can test your backend using any WebSocket client. Here's an example using JavaScript in a browser console:

// Connect to a room
const ws = new WebSocket('ws://localhost:8080/room1');

// Handle incoming messages
ws.onmessage = (event) => {
    console.log('Received:', event.data);
};

// Send a message
ws.send('Hello, PyStrands!');

Or using wscat from the command line:

# Install wscat
npm install -g wscat

# Connect to a room
wscat -c ws://localhost:8080/room1

# Type messages to send
> Hello, PyStrands!
< echo: Hello, PyStrands!

Next Steps

Troubleshooting

Connection Refused

If you see "Connection refused" errors, ensure: 1. The server is running (python -m pystrands server) 2. The host and port in your client match the server settings 3. No firewall is blocking the connection

Binary Download Issues

If the server binary fails to download, you can manually download it from the pystrands-go releases and place it in ~/.pystrands/pystrands-server.