File size: 2,894 Bytes
7916f15
 
 
9204fa7
7916f15
41d3274
 
7916f15
9204fa7
41d3274
9204fa7
 
 
 
7916f15
 
 
 
41d3274
 
7916f15
9204fa7
41d3274
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9204fa7
 
41d3274
 
 
 
 
 
 
7916f15
7d45aaa
7916f15
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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())