Ramesh-vani commited on
Commit
9204fa7
·
verified ·
1 Parent(s): 7d45aaa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -28
app.py CHANGED
@@ -1,56 +1,71 @@
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
  # Check if the key exists in the database
34
- cursor.execute('SELECT client_ws FROM pairs WHERE key=?', (key_to_connect,))
35
  result = cursor.fetchone()
36
 
37
  if result:
38
- other_client_ws = result[0]
39
 
40
- # Pair the clients
41
- await websocket.send(f"Connected to key {key_to_connect}. You are paired with {other_client_ws}")
42
- await other_client_ws.send(f"Connected to key {key_to_connect}. You are paired with {str(websocket)}")
43
 
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
 
@@ -60,4 +75,5 @@ async def main():
60
  await asyncio.Event().wait()
61
 
62
  if __name__ == "__main__":
 
63
  asyncio.run(main())
 
1
  import asyncio
2
  import websockets
 
 
3
  import sqlite3
4
+ import secrets
5
 
6
+ # SQLite database setup
7
+ conn = sqlite3.connect('pairing.db')
8
  cursor = conn.cursor()
9
+
10
+ # Create Pairing table if not exists
11
+ cursor.execute('''
12
+ CREATE TABLE IF NOT EXISTS Pairing (
13
+ key TEXT PRIMARY KEY,
14
+ client_address TEXT
15
+ )
16
+ ''')
17
  conn.commit()
18
 
19
  async def handle_client(websocket, path):
20
  try:
21
+ # Receive a command from the client
22
+ command = await websocket.recv()
23
 
24
+ if command == "create_pair":
25
+ # Create a unique key
26
+ key = secrets.token_hex(16)
27
 
28
+ # Save the key and client address in the database
29
+ cursor.execute('INSERT INTO Pairing (key, client_address) VALUES (?, ?)', (key, str(websocket.remote_address)))
30
  conn.commit()
31
 
32
+ # Inform the client about the generated key
33
+ await websocket.send(f"Your pair key is: {key}")
34
 
35
+ elif command.startswith("connect_to_key"):
36
+ # Extract the key from the command
37
+ key_to_connect = command.split(" ")[1]
38
 
39
  # Check if the key exists in the database
40
+ cursor.execute('SELECT client_address FROM Pairing 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"Connected to {other_client_address}")
48
+ await websocket.send(f"You are paired with {other_client_address}")
49
 
50
+ # Create a bidirectional bridge
51
+ other_client = next(c for c in connected_clients if str(c.remote_address) == other_client_address)
52
+ asyncio.ensure_future(bridge_clients(websocket, other_client))
53
+ asyncio.ensure_future(bridge_clients(other_client, websocket))
54
 
55
  except websockets.exceptions.ConnectionClosed:
56
  pass # Connection closed, handle appropriately
57
 
58
+ async def bridge_clients(source, destination):
59
+ try:
60
+ while True:
61
+ # Receive data from the source client
62
+ data_from_source = await source.recv()
63
+
64
+ # Forward the data to the destination client
65
+ await destination.send(data_from_source)
66
+
67
+ except websockets.exceptions.ConnectionClosed:
68
+ pass # Exit the loop if connection is closed
69
 
70
  start_server = websockets.serve(handle_client, "localhost", 8765)
71
 
 
75
  await asyncio.Event().wait()
76
 
77
  if __name__ == "__main__":
78
+ connected_clients = set()
79
  asyncio.run(main())