Ramesh-vani commited on
Commit
4a70d33
1 Parent(s): 0e1702e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -29
app.py CHANGED
@@ -1,38 +1,28 @@
 
1
  import asyncio
2
  import websockets
3
 
4
- async def run_code(websocket, path):
 
 
5
  try:
6
- print("WebSocket connection established.")
7
-
8
- # Read the code from the WebSocket connection
9
  code = await websocket.recv()
10
- print("Received code:", code)
11
-
12
- # Establish connection to external WebSocket server
13
- async with websockets.connect('wss://ramesh-vani-wspython.hf.space') as web:
14
- print("Connection to external WebSocket server established.")
15
 
16
- await web.send(code)
17
- print("Code sent to external WebSocket server.")
18
- print(code)
19
-
20
  while True:
21
- response = await web.recv()
22
- print("Received response:", response)
23
- await send_message(websocket, response)
24
-
25
- except Exception as e:
26
- print(f'Error: {str(e)}')
27
- await websocket.send(f'Error: {str(e)}')
28
- finally:
29
- print("Closing WebSocket connection.")
30
- await websocket.close()
31
-
32
- async def send_message(websocket, message):
33
- await websocket.send(f'data: {message}')
34
 
35
- start_server = websockets.serve(run_code, "0.0.0.0", 7860)
 
 
 
 
 
36
 
37
- asyncio.get_event_loop().run_until_complete(start_server)
38
- asyncio.get_event_loop().run_forever()
 
1
+ import threading
2
  import asyncio
3
  import websockets
4
 
5
+
6
+ async def websocket_consumer(websocket, path):
7
+
8
  try:
 
 
 
9
  code = await websocket.recv()
10
+ async with websockets.connect('wss://ramesh-vani-wspython.hf.space') as wssocket:
 
 
 
 
11
 
12
+ await wssocket.send(code)
 
 
 
13
  while True:
14
+ response = await wssocket.recv()
15
+ await websocket.send(response)
16
+
17
+ except websockets.exceptions.ConnectionClosedOK:
18
+ pass
 
 
 
 
 
 
 
 
19
 
20
+ class WebSocketThread(threading.Thread):
21
+ def run(self):
22
+ asyncio.set_event_loop(asyncio.new_event_loop())
23
+ start_server = websockets.serve(websocket_consumer, '0.0.0.0', 7860)
24
+ asyncio.get_event_loop().run_until_complete(start_server)
25
+ asyncio.get_event_loop().run_forever()
26
 
27
+ websocket_thread = WebSocketThread()
28
+ websocket_thread.start()