Implementing a Recursive Async Server-Client Architecture with JSON over stdio
Yes, it's possible to implement a server-client architecture application in Python that uses recursive async functions and communicates via JSON over standard input/output. Let's break down how to build this system.
Recursive Async Functions in Python
Python's asyncio library allows for asynchronous programming, and we can create recursive async functions with proper handling:
import asyncio
async def recursive_async_function(data, depth=0, max_depth=5):
if depth >= max_depth:
return data
# Process data asynchronously
await asyncio.sleep(0.1) # Simulating async operation
result = f"Processed {data} at depth {depth}"
# Recursive async call
return await recursive_async_function(result, depth + 1, max_depth)
For deep recursion, we need to be careful with stack limitations. For proper recursive async functions, we may need to use the async_recursion decorator:
from async_recursion import async_recursion
@async_recursion
async def fib(n: int) -> int:
if n <= 1:
return n
return await fib(n-1) + await fib(n-2)
Basic Server-Client Architecture
Let's implement a basic server-client setup using asyncio:
# server.py
import asyncio
import json
async def handle_client(reader, writer):
while True:
data = await reader.read(1024)
if not data:
break
message = json.loads(data.decode())
addr = writer.get_extra_info('peername')
print(f"Received {message} from {addr}")
# Process message (could involve recursive async calls)
response = await process_message(message)
# Send response back
writer.write(json.dumps(response).encode())
await writer.drain()
writer.close()
async def process_message(message):
# This could be a recursive async function
return {"status": "processed", "original": message}
async def start_server():
server = await asyncio.start_server(handle_client, '127.0.0.1', 8888)
async with server:
await server.serve_forever()
asyncio.run(start_server())
# client.py
import asyncio
import json
async def send_request(message):
reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
# Send message
writer.write(json.dumps(message).encode())
await writer.drain()
# Get response
data = await reader.read(1024)
response = json.loads(data.decode())
writer.close()
await writer.wait_closed()
return response
async def main():
response = await send_request({"command": "hello", "data": "world"})
print(f"Received response: {response}")
asyncio.run(main())
JSON Communication over stdio
For stdio-based communication (instead of sockets), we can modify our approach:
# stdio_server.py
import asyncio
import json
import sys
async def handle_stdin():
while True:
# Read content length from stdin
content_length_line = await asyncio.get_event_loop().run_in_executor(
None, sys.stdin.readline
)
if not content_length_line:
break
content_length = int(content_length_line.strip().split(": ")[1])
# Read json content based on content length
content = await asyncio.get_event_loop().run_in_executor(
None, lambda: sys.stdin.read(content_length)
)
message = json.loads(content)
# Process message (potentially using recursive async functions)
response = await process_message(message)
# Write response to stdout
response_json = json.dumps(response)
sys.stdout.write(f"Content-Length: {len(response_json)}\r\n\r\n")
sys.stdout.write(response_json)
sys.stdout.flush()
async def process_message(message, depth=0, max_depth=3):
if depth >= max_depth or "final" in message:
return {"result": message, "depth": depth}
# Recursive processing
processed = {"processed": message, "depth": depth}
return await process_message(processed, depth + 1, max_depth)
asyncio.run(handle_stdin())
Combining into a Single Script
We can combine both server and client functionality into a single script using asyncio tasks:
import asyncio
import json
import sys
from async_recursion import async_recursion
class JSONProtocol:
@staticmethod
def encode(message):
json_str = json.dumps(message)
return f"Content-Length: {len(json_str)}\r\n\r\n{json_str}".encode()
@staticmethod
async def decode(reader):
header = await reader.readline()
if not header:
return None
content_length = int(header.decode().strip().split(": ")[1])
# Skip empty line after header
await reader.readline()
content = await reader.read(content_length)
return json.loads(content.decode())
@async_recursion
async def process_request(request, depth=0, max_depth=5):
if depth >= max_depth or request.get("command") == "stop":
return {"status": "complete", "result": request, "depth": depth}
# Simulate some async processing
await asyncio.sleep(0.1)
# Recursive call with modified request
next_request = {
"command": request.get("command", "default"),
"data": f"Processed {request.get('data', 'empty')} at depth {depth}",
"depth": depth + 1
}
result = await process_request(next_request, depth + 1, max_depth)
return {"previous": request, "next": result, "depth": depth}
async def server_handler(reader, writer):
client_addr = writer.get_extra_info('peername')
print(f"Client connected: {client_addr}")
while True:
try:
request = await JSONProtocol.decode(reader)
if not request:
break
print(f"Processing request: {request}")
# Process using recursive async function
response = await process_request(request)
# Send response
writer.write(JSONProtocol.encode(response))
await writer.drain()
if request.get("command") == "stop":
break
except Exception as e:
print(f"Error processing request: {e}")
break
writer.close()
await writer.wait_closed()
print(f"Client disconnected: {client_addr}")
async def client_task():
print("Starting client...")
await asyncio.sleep(1) # Give server time to start
try:
reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
# Send initial request
request = {"command": "start", "data": "initial data"}
writer.write(JSONProtocol.encode(request))
await writer.drain()
# Get response
response = await JSONProtocol.decode(reader)
print(f"Received response: {response}")
# Send stop command
request = {"command": "stop", "data": "final data"}
writer.write(JSONProtocol.encode(request))
await writer.drain()
# Get final response
response = await JSONProtocol.decode(reader)
print(f"Received final response: {response}")
writer.close()
await writer.wait_closed()
except Exception as e:
print(f"Client error: {e}")
async def start_server():
server = await asyncio.start_server(server_handler, '127.0.0.1', 8888)
async with server:
print(f"Server running on {server.sockets.getsockname()}")
await server.serve_forever()
async def main():
# Run server and client as separate tasks
server_task = asyncio.create_task(start_server())
client_task_obj = asyncio.create_task(client_task())
# Wait for client to finish
await client_task_obj
# Cancel server after client is done
server_task.cancel()
try:
await server_task
except asyncio.CancelledError:
print("Server stopped")
if __name__ == "__main__":
asyncio.run(main())
Pure stdio Communication Example
For pure stdio communication (no sockets):
import asyncio
import json
import sys
from async_recursion import async_recursion
@async_recursion
async def process_message(message, depth=0, max_depth=3):
if depth >= max_depth:
return {"final_result": message, "depth": depth}
# Simulate async processing
await asyncio.sleep(0.1)
processed = {"processed_from": message, "at_depth": depth}
# Recursive call
return await process_message(processed, depth + 1, max_depth)
async def handle_stdio():
loop = asyncio.get_event_loop()
while True:
# Read from stdin
try:
line = await loop.run_in_executor(None, sys.stdin.readline)
if not line or line.strip() == "exit":
break
try:
# Parse JSON input
message = json.loads(line)
# Process with recursive async function
result = await process_message(message)
# Output result to stdout
sys.stdout.write(json.dumps(result) + "\n")
sys.stdout.flush()
except json.JSONDecodeError:
sys.stdout.write(json.dumps({"error": "Invalid JSON"}) + "\n")
sys.stdout.flush()
except Exception as e:
sys.stdout.write(json.dumps({"error": str(e)}) + "\n")
sys.stdout.flush()
if __name__ == "__main__":
asyncio.run(handle_stdio())
Conclusion
Building a server-client architecture with recursive async functions and JSON over stdio is entirely feasible in Python. The core components are:
- Async recursive functions using
async/await syntax, potentially with the async_recursion decorator for deep recursion
- Server-client architecture using either sockets with
asyncio or stdio
- JSON communication for serializing/deserializing data between components
The approach provides flexibility and can be adapted to various use cases, whether you need network-based communication or process-to-process communication via standard streams.