Skip to content

Instantly share code, notes, and snippets.

@yashmarathe21
Created May 10, 2025 13:32
Show Gist options
  • Save yashmarathe21/d21889bf0d96115bf6d22627163abce9 to your computer and use it in GitHub Desktop.
Save yashmarathe21/d21889bf0d96115bf6d22627163abce9 to your computer and use it in GitHub Desktop.
import socket
import threading
# === Configuration ===
PORT = 50008
CHUNK_SIZE = 1024 * 2
# === Server Setup ===
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("0.0.0.0", PORT))
print(f"[SERVER] Voice relay server started on port {PORT}")
# === Shared State ===
clients = {} # name -> (ip, port)
call_map = {} # caller -> target
connected_pairs = set() # (caller, target) pairs with both clients registered
lock = threading.Lock()
# === Main Handler Loop ===
def handle_client():
while True:
try:
data, addr = sock.recvfrom(4096)
print(f"[SERVER] Packet received from {addr}")
# === Registration Message ===
if data.startswith(b"REGISTER:"):
try:
message = data.decode('utf-8')
print(f"[SERVER] Registration message received: {message}")
parts = message.strip().split(":")
if len(parts) < 3:
print("[SERVER] Invalid registration format")
continue
name = parts[1]
target = parts[2]
with lock:
clients[name] = addr
call_map[name] = target
print(f"[SERVER] Registered client '{name}' at {addr} wants to call '{target}'")
# Check if target already registered
if target in clients:
print(f"[SERVER] Target '{target}' is online.")
connected_pairs.add((name, target))
if call_map.get(target) == name:
connected_pairs.add((target, name))
print(f"[SERVER] Bi-directional call ready between '{name}' and '{target}'")
else:
print(f"[SERVER] Target '{target}' not yet online.")
except Exception as e:
print(f"[SERVER] Error during registration: {e}")
# === Audio Packet ===
else:
sender_name = None
with lock:
for name, client_addr in clients.items():
if client_addr == addr:
sender_name = name
break
if sender_name is None:
print("[SERVER] Sender not recognized. Ignoring packet.")
continue
with lock:
target_name = call_map.get(sender_name)
if not target_name:
print(f"[SERVER] No target set for '{sender_name}'")
continue
# Check if the connection is active
if (sender_name, target_name) in connected_pairs:
target_addr = clients.get(target_name)
if target_addr:
sock.sendto(data, target_addr)
print(f"[SERVER] Forwarded audio from '{sender_name}' to '{target_name}'")
else:
print(f"[SERVER] Target '{target_name}' address not found.")
else:
print(f"[SERVER] '{sender_name}' is waiting for '{target_name}' to come online.")
except Exception as e:
print(f"[SERVER] General error: {e}")
# === Start Server ===
handle_client()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment