-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver4.py
More file actions
executable file
·71 lines (55 loc) · 2.2 KB
/
Copy pathserver4.py
File metadata and controls
executable file
·71 lines (55 loc) · 2.2 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
#!/usr/bin/env python3.7
################################################################################
# Четвертая версия сервера.
# Актуальная.
################################################################################
import asyncio
import logging
import random
import quart
app = quart.Quart(__name__, template_folder="templates", static_folder="static")
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format="> %(asctime)-15s %(levelname)-8s || %(message)s")
@app.route("/")
async def index():
return await quart.render_template("index.html")
@app.route("/p/<name>")
async def handle_p(name):
return await quart.render_template(f"p_{name}.html")
@app.route("/j/<name>")
async def handle_j(name):
return await quart.render_template(f"j_{name}.js")
queues = set()
@app.websocket("/ws")
async def handle_ws():
global queues
user = f"{quart.websocket.remote_addr}#{random.randint(1000, 9999)}"
queue = asyncio.Queue()
async def sending():
while True:
data = await queue.get()
# Раскомментируйте строчку ниже, чтобы добавить случайные задержки в синхронизации.
# await asyncio.sleep(random.random() / 5.0)
log.info("Пользователь %s: SEND[%r]", user, data)
await quart.websocket.send(data)
async def receiving():
while True:
data = await quart.websocket.receive()
log.info("Пользователь %s: RECV[%r]", user, data)
for queue1 in queues:
await queue1.put(data)
try:
log.info("Пользователь %s подключился :)", user)
queues.add(queue)
producer = asyncio.create_task(sending())
consumer = asyncio.create_task(receiving())
await asyncio.gather(producer, consumer)
finally:
log.info("Пользователь %s отключился :(", user)
queues.remove(queue)
def main():
app.config.from_mapping(DEBUG=True, ENV="dev")
#app.run(host="0.0.0.0", port=80)
app.run(host="0.0.0.0")
if __name__ == "__main__":
main()