Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- Dockerfile +22 -0
- app.py +32 -0
Dockerfile
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.11
|
2 |
+
|
3 |
+
# Create a non-root user
|
4 |
+
RUN useradd -ms /bin/bash myuser
|
5 |
+
|
6 |
+
# Set the working directory
|
7 |
+
WORKDIR /code
|
8 |
+
|
9 |
+
# Copy the project files
|
10 |
+
COPY . .
|
11 |
+
|
12 |
+
# Install Python dependencies
|
13 |
+
RUN pip install websockets fastapi uvicorn
|
14 |
+
|
15 |
+
# Change ownership of the code directory to the non-root user
|
16 |
+
RUN chown -R myuser:myuser /code
|
17 |
+
|
18 |
+
# Switch to the non-root user
|
19 |
+
USER myuser
|
20 |
+
|
21 |
+
# Set the command to run your application
|
22 |
+
CMD ["python", "app.py"]
|
app.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException
|
2 |
+
from typing import Dict
|
3 |
+
app = FastAPI()
|
4 |
+
clients: Dict[str, WebSocket] = {}
|
5 |
+
@app.get("/clients")
|
6 |
+
def get_clients():
|
7 |
+
return list(clients.keys())
|
8 |
+
@app.websocket("/ws/{client_id}")
|
9 |
+
async def websocket_endpoint(websocket: WebSocket, client_id: str):
|
10 |
+
await websocket.accept()
|
11 |
+
clients[client_id] = websocket
|
12 |
+
print(f"Client {client_id} connected.")
|
13 |
+
try:
|
14 |
+
while True:
|
15 |
+
data = await websocket.receive_text()
|
16 |
+
message_parts = data.split(":", 1)
|
17 |
+
if len(message_parts) == 2:
|
18 |
+
target_client_id = message_parts[0].strip()
|
19 |
+
msg_content = message_parts[1].strip()
|
20 |
+
if target_client_id in clients:
|
21 |
+
target_websocket = clients[target_client_id]
|
22 |
+
await target_websocket.send_text(f"{client_id}: {msg_content}")
|
23 |
+
else:
|
24 |
+
await websocket.send_text(f"Error: Client {target_client_id} not found.")
|
25 |
+
else:
|
26 |
+
await websocket.send_text("Error: Invalid message format. Use 'target_id:message'.")
|
27 |
+
except WebSocketDisconnect:
|
28 |
+
del clients[client_id]
|
29 |
+
print(f"Client disconnected: {client_id}")
|
30 |
+
if __name__ == "__main__":
|
31 |
+
import uvicorn
|
32 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|