Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
21 |
+
@app.get("/")
|
22 |
+
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('ws://' + 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>
|
41 |
+
</body>
|
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)
|