-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket_server.py
More file actions
159 lines (130 loc) · 4.56 KB
/
websocket_server.py
File metadata and controls
159 lines (130 loc) · 4.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import json
import os
import shutil
from typing import List
import uvicorn
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, UploadFile, File, Header, Request
from fastapi.responses import HTMLResponse
from starlette.responses import FileResponse
app = FastAPI()
html = """
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<h2>Your ID: <span id="ws-id"></span></h2>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
<form action="/upload/" method="post" enctype="multipart/form-data" target="dummyframe">
<input name="file" id="file" type="file">
<input type="submit" value="uploadFile上传">
</form>
<ul id='messages'>
</ul>
<script>
var client_id = Date.now()
var host = location.host
document.querySelector("#ws-id").textContent = client_id;
var ws = new WebSocket(`ws://${host}/ws/msg/${client_id}`);
ws.onmessage = function (event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var msg = JSON.parse(event.data)
console.log("type", msg.type, event)
var msg_type = msg.type
if (msg_type == 'text'){
var content = document.createTextNode(msg.data)}
else {
var content = document.createElement('a')
content.href = '/file/' + msg.filename
content.innerText = msg.filename
}
message.appendChild(content)
messages.appendChild(message)
};
function sendMessage(event) {
var input = document.getElementById("messageText")
var data = input.value;
form = {"type":"text", "data":data, "client_id":client_id}
ws.send(JSON.stringify(form))
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
"""
class ConnectionManager:
def __init__(self):
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
async def send_personal_message(self, message: str, websocket: WebSocket):
await websocket.send_text(message)
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_text(message)
manager = ConnectionManager()
file_manager = ConnectionManager()
@app.get("/")
async def get():
# return HTMLResponse(html)
return FileResponse("index.html")
@app.websocket("/ws/msg/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
await manager.connect(websocket)
try:
while True:
json_data = await websocket.receive_text()
data = json.loads(json_data)
form = {
"type": data.get("type"),
"data": data.get("data"),
"client_id": client_id
}
await manager.broadcast(json.dumps(form))
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast(f"Client #{client_id} left the chat")
def save_path(folder):
if not os.path.exists(folder):
os.makedirs(folder)
path = os.path.join(folder)
print("path", path)
return path + "/"
@app.post("/upload/")
async def create_upload_file(client_id: int, request: Request, file: UploadFile = File(...)):
try:
path = save_path("files")
size = int(request.headers.get("content-length", 1000000))
if size <= 83886080:
print("file size", size)
filename = file.filename
filepath = path + filename
with open(filepath, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
form = {"type": "file", "data": filename, "client_id": client_id}
await manager.broadcast(json.dumps(form))
else:
print("too large file")
return
except Exception as e:
print("save file error", e)
# return {"filename": file.filename}
@app.get("/file/{filename}")
def file_download(filename):
path = save_path("files")
file_path = path + filename
return FileResponse(file_path)
if __name__ == '__main__':
# uvicorn.run(app, host="0.0.0.0", port=8000, debug=True)
uvicorn.run(app, host="localhost", port=8000, debug=True)