# lib_jsonbus **Repository Path**: creatorgg/lib_jsonbus ## Basic Information - **Project Name**: lib_jsonbus - **Description**: No description available - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-01-28 - **Last Updated**: 2026-01-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # JsonBus A simple JSON-based communication library using Unix domain sockets for inter-process communication (IPC) on Linux/Unix systems. The server uses asyncio for efficient asynchronous handling of multiple concurrent clients. ## Features - **Unix Domain Sockets**: Efficient local IPC without network overhead - **JSON Serialization**: Automatic JSON encoding/decoding - **Length-Prefixed Protocol**: 4-byte length prefix for reliable message framing - **Async Server**: Server uses asyncio for efficient concurrent client handling - **Multi-Client Support**: Server can handle multiple concurrent client connections - **Default Echo Handler**: Built-in handler that echoes received data back - **Custom Handlers**: Support for custom request/response handlers - **Logging Support**: Optional logging for debugging and error tracking - **Context Manager Support**: Clean resource management with `async with` statements ## Installation ### Install from Git Repository ```bash pip install git+https://gitee.com/creatorgg/lib_jsonbus ``` ### Install from Local Directory ```bash pip install . ``` ## Protocol The communication protocol uses a simple length-prefixed format: ``` [4 bytes: payload length (big-endian unsigned integer)] + [JSON payload] ``` For example: - Data: `{"message": "hello"}` - JSON string: `{"message": "hello"}` (22 bytes) - Length prefix: `0x00000016` (22 in big-endian) - Complete message: `0x00000016{"message": "hello"}` ## Quick Start ### Basic Server (Async) The JsonBus server uses asyncio for efficient asynchronous handling. You need to run it in an async context: ```python import asyncio from jsonbus import JsonBusServer async def main(): # Create server with custom socket path server = JsonBusServer('/tmp/my_jsonbus.sock') # Start the server (this blocks until stopped) await server.start() # Run the async server asyncio.run(main()) ``` ### Basic Client ```python from jsonbus import JsonBusClient # Create client client = JsonBusClient('/tmp/my_jsonbus.sock') # Connect to server client.connect() # Send data and receive response response = client.send({"message": "Hello, Server!"}) print(response) # {"message": "Hello, Server!"} # Close connection client.close() ``` ### Using Context Managers **Async Server (requires async context):** ```python import asyncio from jsonbus import JsonBusServer async def main(): async with JsonBusServer('/tmp/my_jsonbus.sock') as server: # Server is running here # You can add other async operations await asyncio.sleep(10) # Run for 10 seconds # Server automatically stopped asyncio.run(main()) ``` **Client (synchronous):** ```python from jsonbus import JsonBusClient with JsonBusClient('/tmp/my_jsonbus.sock') as client: response = client.send({"data": [1, 2, 3]}) print(response) # Connection automatically closed ``` ### Custom Handler ```python import asyncio from jsonbus import JsonBusServer async def custom_handler(data): """Custom async handler that processes data""" if data.get('action') == 'add': # Can perform async operations here await asyncio.sleep(0.1) return {'result': data.get('a', 0) + data.get('b', 0)} elif data.get('action') == 'multiply': await asyncio.sleep(0.1) return {'result': data.get('a', 0) * data.get('b', 0)} else: return {'error': 'Unknown action'} async def main(): server = JsonBusServer('/tmp/my_jsonbus.sock', handler=custom_handler) await server.start() asyncio.run(main()) ``` **Important:** Handlers must be async functions (use `async def`) and can perform async operations like database queries, HTTP requests, or file I/O. ### Logging Support Both `JsonBusServer` and `JsonBusClient` support optional logging for debugging and error tracking: ```python import logging from jsonbus import JsonBusServer, JsonBusClient # Configure logging logger = logging.getLogger('jsonbus') logger.setLevel(logging.DEBUG) # Create console handler with formatting console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) console_handler.setFormatter(formatter) logger.addHandler(console_handler) # Set logger for server server = JsonBusServer('/tmp/my_jsonbus.sock') server.set_logger(logger) server.start() # Set logger for client client = JsonBusClient('/tmp/my_jsonbus.sock') client.set_logger(logger) client.connect() ``` **Log Levels:** - `logger.info()`: Informational messages (server start/stop, client connect/disconnect) - `logger.error()`: Error messages (connection failures, protocol errors, communication errors) - `logger.warning()`: Warning messages (cleanup errors, socket close issues) **Benefits:** - Debug issues without modifying code - Track client connections and disconnections - Monitor errors in production - Integrate with existing logging infrastructure - Log to files, syslog, or other destinations ## API Reference ### JsonBusServer (Async) ```python class JsonBusServer: def __init__(self, socket_path: str, handler: Optional[Callable[[Any], Awaitable[Any]]] = None): """ Initialize the async server. Args: socket_path: Path to the Unix domain socket file handler: Optional custom async handler function. Defaults to echo handler. The handler must be an async function (defined with `async def`) that accepts a deserialized JSON object and returns a JSON-serializable object. """ def set_logger(self, logger: logging.Logger): """ Set the logger for the server. Args: logger: A logging.Logger instance to use for logging """ async def start(self): """Start the async server and accept connections (coroutine).""" async def stop(self): """Stop the async server and clean up resources (coroutine).""" ``` **Note:** The server methods are async and must be called with `await` in an async context. The server uses `async with` for context manager support. ### JsonBusClient ```python class JsonBusClient: def __init__(self, socket_path: str): """Initialize the client with socket path.""" def set_logger(self, logger: logging.Logger): """ Set the logger for the client. Args: logger: A logging.Logger instance to use for logging """ def connect(self): """Connect to the server.""" def send(self, data: Any) -> Any: """ Send data to the server and receive a response. Args: data: JSON-serializable data to send Returns: Response data from the server (deserialized JSON object) """ def close(self): """Close the connection to the server.""" def is_connected(self) -> bool: """Check if the client is connected to the server.""" ``` ## Testing Run the integration tests: ```bash python -m pytest tests/ ``` Or run directly: ```bash python tests/test_integration.py ``` **Note:** The tests use threading to run the async server in a background thread while synchronous clients connect and communicate. This demonstrates that the async server can work seamlessly with synchronous clients. ## Example: Multi-Process Communication ```python # server.py (async) import asyncio import time from jsonbus import JsonBusServer async def handler(data): """Process requests from clients""" # Can perform async operations await asyncio.sleep(0.01) return {'echo': data, 'timestamp': time.time()} async def main(): server = JsonBusServer('/tmp/example.sock', handler=handler) await server.start() asyncio.run(main()) ``` ```python # client.py from jsonbus import JsonBusClient client = JsonBusClient('/tmp/example.sock') client.connect() response = client.send({'message': 'Hello from client'}) print(response) client.close() ``` ## Limitations - Unix domain sockets are only available on Unix-like systems (Linux, macOS, BSD) - Not available on Windows (would need to use named pipes or TCP sockets) - Messages must be JSON-serializable ## License MIT License ## Contributing Contributions are welcome! Please feel free to submit a Pull Request.