Ramesh-vani commited on
Commit
ff15b41
·
verified ·
1 Parent(s): 41d3274

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -57
app.py CHANGED
@@ -1,73 +1,56 @@
1
  import asyncio
2
  import websockets
 
 
3
  import sqlite3
4
- import secrets
5
 
6
- # Connect to SQLite database (create it if not exists)
7
- conn = sqlite3.connect('client_pairs.db')
8
  cursor = conn.cursor()
9
- cursor.execute('''
10
- CREATE TABLE IF NOT EXISTS pairs (
11
- key TEXT PRIMARY KEY,
12
- client_address TEXT
13
- )
14
- ''')
15
  conn.commit()
16
 
17
  async def handle_client(websocket, path):
18
  try:
19
- # Inform the client about successful connection
20
- await websocket.send("Connected to the server")
21
-
22
- while True:
23
- command = await websocket.recv()
24
-
25
- if command == "create_pair_key":
26
- # Generate a unique key
27
- pair_key = secrets.token_urlsafe(8)
28
-
29
- # Save the key and client address in the database
30
- cursor.execute("INSERT INTO pairs (key, client_address) VALUES (?, ?)", (pair_key, str(websocket.remote_address)))
31
- conn.commit()
32
-
33
- # Send the generated key to the client
34
- await websocket.send(f"Pair key created: {pair_key}")
35
-
36
- elif command.startswith("connect_to_key "):
37
- key_to_connect = command.split(" ")[1]
38
-
39
- # Check if the key exists in the database
40
- cursor.execute("SELECT client_address FROM pairs WHERE key=?", (key_to_connect,))
41
- result = cursor.fetchone()
42
-
43
- if result:
44
- other_client_address = result[0]
45
-
46
- # Inform both clients about the successful pairing
47
- await websocket.send(f"Paired with {other_client_address}")
48
- await websocket.send(f"Connected to {websocket.remote_address}")
49
- other_client = next((client for client in connected_clients if str(client.remote_address) == other_client_address), None)
50
-
51
- if other_client:
52
- await other_client.send(f"Paired with {websocket.remote_address}")
53
- await other_client.send(f"Connected to {other_client.remote_address}")
54
- else:
55
- await websocket.send("Invalid pair key")
56
-
57
  else:
58
- # Broadcast messages to all connected clients
59
- for client in connected_clients:
60
- if client != websocket:
61
- await client.send(f"Client says: {command}")
62
 
63
  except websockets.exceptions.ConnectionClosed:
64
- pass
65
- finally:
66
- # Remove the client from the set upon disconnection
67
- connected_clients.remove(websocket)
68
 
69
- # Set to store connected clients
70
- connected_clients = set()
 
71
 
72
  start_server = websockets.serve(handle_client, "localhost", 8765)
73
 
 
1
  import asyncio
2
  import websockets
3
+ import random
4
+ import string
5
  import sqlite3
 
6
 
7
+ # Database setup (using SQLite for simplicity)
8
+ conn = sqlite3.connect('pairing_database.db')
9
  cursor = conn.cursor()
10
+ cursor.execute('CREATE TABLE IF NOT EXISTS pairs (key TEXT, client_ws TEXT)')
 
 
 
 
 
11
  conn.commit()
12
 
13
  async def handle_client(websocket, path):
14
  try:
15
+ # Receive the client's request (create a pair or connect to a key)
16
+ request_type = await websocket.recv()
17
+
18
+ if request_type == "create_pair":
19
+ # Generate a unique key
20
+ unique_key = generate_key()
21
+
22
+ # Save the key and associate it with the current client in the database
23
+ cursor.execute('INSERT INTO pairs VALUES (?, ?)', (unique_key, str(websocket)))
24
+ conn.commit()
25
+
26
+ # Inform the client about the created key
27
+ await websocket.send(f"Pair key created: {unique_key}")
28
+
29
+ elif request_type == "connect_to_key":
30
+ # Receive the key from the client
31
+ key_to_connect = await websocket.recv()
32
+
33
+ # Retrieve all clients associated with the key from the database
34
+ cursor.execute('SELECT client_ws FROM pairs WHERE key=?', (key_to_connect,))
35
+ results = cursor.fetchall()
36
+
37
+ if results:
38
+ # Pair the current client with all clients associated with the key
39
+ for result in results:
40
+ other_client_ws = result[0]
41
+ if other_client_ws != str(websocket):
42
+ await websocket.send(f"Connected to key {key_to_connect}. You are paired with {other_client_ws}")
43
+ await other_client_ws.send(f"Connected to key {key_to_connect}. You are paired with {str(websocket)}")
 
 
 
 
 
 
 
 
 
44
  else:
45
+ # Inform the client that the key does not exist
46
+ await websocket.send(f"Key {key_to_connect} does not exist.")
 
 
47
 
48
  except websockets.exceptions.ConnectionClosed:
49
+ pass # Connection closed, handle appropriately
 
 
 
50
 
51
+ def generate_key():
52
+ # Generate a random key (you might want to implement a more robust key generation logic)
53
+ return ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))
54
 
55
  start_server = websockets.serve(handle_client, "localhost", 8765)
56