Spaces:
Running
Running
import asyncio | |
import websockets | |
import sqlite3 | |
import secrets | |
# Connect to SQLite database (create it if not exists) | |
conn = sqlite3.connect('client_pairs.db') | |
cursor = conn.cursor() | |
cursor.execute(''' | |
CREATE TABLE IF NOT EXISTS pairs ( | |
key TEXT PRIMARY KEY, | |
client_address TEXT | |
) | |
''') | |
conn.commit() | |
async def handle_client(websocket, path): | |
try: | |
# Inform the client about successful connection | |
await websocket.send("Connected to the server") | |
while True: | |
command = await websocket.recv() | |
if command == "create_pair_key": | |
# Generate a unique key | |
pair_key = secrets.token_urlsafe(8) | |
# Save the key and client address in the database | |
cursor.execute("INSERT INTO pairs (key, client_address) VALUES (?, ?)", (pair_key, str(websocket.remote_address))) | |
conn.commit() | |
# Send the generated key to the client | |
await websocket.send(f"Pair key created: {pair_key}") | |
elif command.startswith("connect_to_key "): | |
key_to_connect = command.split(" ")[1] | |
# Check if the key exists in the database | |
cursor.execute("SELECT client_address FROM pairs WHERE key=?", (key_to_connect,)) | |
result = cursor.fetchone() | |
if result: | |
other_client_address = result[0] | |
# Inform both clients about the successful pairing | |
await websocket.send(f"Paired with {other_client_address}") | |
await websocket.send(f"Connected to {websocket.remote_address}") | |
other_client = next((client for client in connected_clients if str(client.remote_address) == other_client_address), None) | |
if other_client: | |
await other_client.send(f"Paired with {websocket.remote_address}") | |
await other_client.send(f"Connected to {other_client.remote_address}") | |
else: | |
await websocket.send("Invalid pair key") | |
else: | |
# Broadcast messages to all connected clients | |
for client in connected_clients: | |
if client != websocket: | |
await client.send(f"Client says: {command}") | |
except websockets.exceptions.ConnectionClosed: | |
pass | |
finally: | |
# Remove the client from the set upon disconnection | |
connected_clients.remove(websocket) | |
# Set to store connected clients | |
connected_clients = set() | |
start_server = websockets.serve(handle_client, "localhost", 8765) | |
async def main(): | |
print("WebSocket server is running. Waiting for connections...") | |
await start_server | |
await asyncio.Event().wait() | |
if __name__ == "__main__": | |
asyncio.run(main()) | |