Pycrdt WebSocket Connector

0.16.0 · active · verified Thu Apr 16

Pycrdt-websocket provides a WebSocket connector for `pycrdt`, enabling real-time, collaborative document synchronization using Y-CRDTs over a network. It facilitates both server-side handling of Y-CRDT documents and client-side connections. The library is actively maintained with frequent minor releases, typically addressing bug fixes and compatibility updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic pycrdt-websocket setup with a server and a client. The server initializes a YDoc and listens for connections, while the client connects to synchronize its own YDoc. It shows how text changes are synchronized in real-time.

import asyncio
from pycrdt import YDoc, YText
from pycrdt.websocket import WebSocketServer, YDocRoom

async def server_main():
    # Initialize a Y-CRDT document for the server
    ydoc = YDoc()
    with ydoc.transaction():
        text = ydoc.get_text('my_text')
        text += 'Hello from server!'

    # Create a WebSocket server that manages rooms
    server = WebSocketServer(ydoc, 'ws://127.0.0.1:1234')
    print("Server starting on ws://127.0.0.1:1234")
    await server.start()
    await asyncio.sleep(5) # Keep server running for a bit
    await server.stop()
    print("Server stopped")

async def client_main():
    await asyncio.sleep(1) # Give server a moment to start
    print("Client connecting...")
    # Connect to the server with a YDocRoom
    client_ydoc = YDoc()
    room = YDocRoom(client_ydoc, 'ws://127.0.0.1:1234')
    await room.connect()

    # Access the shared text
    shared_text = client_ydoc.get_text('my_text')
    print(f"Client received: '{shared_text}'")

    with client_ydoc.transaction():
        shared_text.append(' And client!')
    print(f"Client sent: '{shared_text}'")

    await asyncio.sleep(1) # Allow changes to propagate
    await room.disconnect()
    print("Client disconnected")

async def main():
    server_task = asyncio.create_task(server_main())
    client_task = asyncio.create_task(client_main())
    await asyncio.gather(server_task, client_task)

if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →