Almaatla commited on
Commit
050938e
·
verified ·
1 Parent(s): 0242cbc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -11
app.py CHANGED
@@ -1,20 +1,30 @@
1
  from fastapi import FastAPI, WebSocket
2
  from fastapi.responses import HTMLResponse
3
  import uvicorn
 
4
 
5
  app = FastAPI()
6
 
7
  class ConnectionManager:
8
  def __init__(self):
9
- self.active_connections = []
10
 
11
  async def connect(self, websocket: WebSocket):
12
  await websocket.accept()
13
- self.active_connections.append(websocket)
14
 
15
- async def broadcast(self, message: str):
16
- for connection in self.active_connections:
17
- await connection.send_text(message)
 
 
 
 
 
 
 
 
 
18
 
19
  manager = ConnectionManager()
20
 
@@ -23,18 +33,27 @@ async def get():
23
  return HTMLResponse("""
24
  <html>
25
  <body>
26
- <h1>Simple Chat</h1>
27
  <div id="chat" style="height:300px;overflow-y:scroll"></div>
28
  <input id="msg" type="text">
29
  <button onclick="send()">Send</button>
30
  <script>
31
  const ws = new WebSocket('wss://' + window.location.host + '/ws');
 
 
 
32
  ws.onmessage = e => {
 
33
  document.getElementById('chat').innerHTML +=
34
- `<div>${e.data}</div>`;
35
  };
36
  const send = () => {
37
- ws.send(document.getElementById('msg').value);
 
 
 
 
 
38
  document.getElementById('msg').value = '';
39
  };
40
  </script>
@@ -42,15 +61,52 @@ async def get():
42
  </html>
43
  """)
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  @app.websocket("/ws")
46
  async def websocket_endpoint(websocket: WebSocket):
47
  await manager.connect(websocket)
48
  try:
 
 
 
 
 
 
 
49
  while True:
50
  message = await websocket.receive_text()
51
- await manager.broadcast(f"User: {message}")
52
- except:
53
- manager.active_connections.remove(websocket)
 
 
 
54
 
55
  if __name__ == "__main__":
56
  uvicorn.run(app, host="0.0.0.0", port=8000)
 
1
  from fastapi import FastAPI, WebSocket
2
  from fastapi.responses import HTMLResponse
3
  import uvicorn
4
+ import json
5
 
6
  app = FastAPI()
7
 
8
  class ConnectionManager:
9
  def __init__(self):
10
+ self.active_connections = {} # WebSocket: source
11
 
12
  async def connect(self, websocket: WebSocket):
13
  await websocket.accept()
14
+ self.active_connections[websocket] = None
15
 
16
+ def set_source(self, websocket: WebSocket, source: str):
17
+ if websocket in self.active_connections:
18
+ self.active_connections[websocket] = source
19
+
20
+ async def send_to_destination(self, destination: str, message: str):
21
+ for ws, src in self.active_connections.items():
22
+ if src == destination:
23
+ await ws.send_text(message)
24
+
25
+ def remove(self, websocket: WebSocket):
26
+ if websocket in self.active_connections:
27
+ del self.active_connections[websocket]
28
 
29
  manager = ConnectionManager()
30
 
 
33
  return HTMLResponse("""
34
  <html>
35
  <body>
36
+ <h1>Chat Client</h1>
37
  <div id="chat" style="height:300px;overflow-y:scroll"></div>
38
  <input id="msg" type="text">
39
  <button onclick="send()">Send</button>
40
  <script>
41
  const ws = new WebSocket('wss://' + window.location.host + '/ws');
42
+ ws.onopen = () => {
43
+ ws.send(JSON.stringify({ source: 'user' }));
44
+ };
45
  ws.onmessage = e => {
46
+ const msg = JSON.parse(e.data);
47
  document.getElementById('chat').innerHTML +=
48
+ `<div>${msg.content}</div>`;
49
  };
50
  const send = () => {
51
+ const message = {
52
+ content: document.getElementById('msg').value,
53
+ source: 'user',
54
+ destination: 'proxy'
55
+ };
56
+ ws.send(JSON.stringify(message));
57
  document.getElementById('msg').value = '';
58
  };
59
  </script>
 
61
  </html>
62
  """)
63
 
64
+ @app.get("/proxy")
65
+ async def get_proxy():
66
+ return HTMLResponse("""
67
+ <html>
68
+ <body>
69
+ <h1>Proxy Client</h1>
70
+ <script>
71
+ const ws = new WebSocket('wss://' + window.location.host + '/ws');
72
+ ws.onopen = () => {
73
+ ws.send(JSON.stringify({ source: 'proxy' }));
74
+ };
75
+ ws.onmessage = e => {
76
+ const msg = JSON.parse(e.data);
77
+ if (msg.destination === 'proxy') {
78
+ const response = {
79
+ content: "Hello user!",
80
+ source: 'proxy',
81
+ destination: 'user'
82
+ };
83
+ ws.send(JSON.stringify(response));
84
+ }
85
+ };
86
+ </script>
87
+ </body>
88
+ </html>
89
+ """)
90
+
91
  @app.websocket("/ws")
92
  async def websocket_endpoint(websocket: WebSocket):
93
  await manager.connect(websocket)
94
  try:
95
+ # Handle initial source identification
96
+ data = await websocket.receive_text()
97
+ init_msg = json.loads(data)
98
+ if 'source' in init_msg:
99
+ manager.set_source(websocket, init_msg['source'])
100
+
101
+ # Handle messages
102
  while True:
103
  message = await websocket.receive_text()
104
+ msg_data = json.loads(message)
105
+ await manager.send_to_destination(msg_data['destination'], message)
106
+
107
+ except Exception as e:
108
+ manager.remove(websocket)
109
+ await websocket.close()
110
 
111
  if __name__ == "__main__":
112
  uvicorn.run(app, host="0.0.0.0", port=8000)