backendD / main.py
Hanzo03's picture
init
ab77fd3
# main.py (Simplified for Pure WebSockets)
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
# πŸ›‘ REMOVE: from aiortc import RTCPeerConnection, RTCSessionDescription, ...
import json
import re
# ... (rest of imports)
app = FastAPI()
# ... (CORS setup remains) ...
# πŸ›‘ REMOVE: ice_servers and rtc_config
# πŸš€ NEW: Pure WebSocket endpoint for RPC
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
print("βœ… WebSocket connected for RPC")
try:
while True:
# Receive RPC message from the client
message = await websocket.receive_text()
print("πŸ“© Received:", message)
try:
rpc = json.loads(message)
result = handle_rpc(rpc)
response = json.dumps({
"jsonrpc": "2.0",
"id": rpc["id"],
"result": result,
})
# Send the RPC result back over the WebSocket
await websocket.send_text(response)
except json.JSONDecodeError:
print(f"Error decoding RPC message: {message}")
except WebSocketDisconnect:
print("πŸ”Œ WebSocket disconnected.")
# No RTCPeerConnection cleanup needed!
# βœ… Your RPC logic stays the same
def handle_rpc(rpc):
method = rpc.get("method")
params = rpc.get("params", {})
if method == "echo":
return params.get("message", "")
elif method == "process":
message = params.get("message", "").lower()
# Add
match = re.match(r"add (\d+) and (\d+)", message)
if match:
x, y = map(int, match.groups())
return x + y
# Subtract
match = re.match(r"subtract (\d+) from (\d+)", message)
if match:
y, x = map(int, match.groups())
return x - y
# Multiply
match = re.match(r"multiply (\d+) and (\d+)", message)
if match:
x, y = map(int, match.groups())
return x * y
# Divide
match = re.match(r"divide (\d+) by (\d+)", message)
if match:
x, y = map(int, match.groups())
return round(x / y, 2) if y != 0 else "Division by zero"
return "Unknown command"
else:
return "Unknown method"
print("βœ… FastAPI WebRTC backend with TURN is ready")