-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket-server.py
More file actions
executable file
·40 lines (32 loc) · 1.08 KB
/
websocket-server.py
File metadata and controls
executable file
·40 lines (32 loc) · 1.08 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
#!/usr/bin/env python3
import asyncio
from collections import deque
from datetime import datetime, timezone
import websockets
CLIENTS = set()
MESSAGE_HISTORY = deque(maxlen=1024)
async def handler(websocket: websockets.WebSocketServerProtocol):
CLIENTS.add(websocket)
try:
for socket_message in MESSAGE_HISTORY:
await websocket.send(socket_message)
while True:
message = await websocket.recv()
if len(message) > 1024:
await websocket.close()
break
timestamp = int(datetime.now(timezone.utc).timestamp()).to_bytes(
6, byteorder="big"
)
socket_message = timestamp + message
MESSAGE_HISTORY.append(socket_message)
websockets.broadcast(CLIENTS, socket_message)
except websockets.ConnectionClosed:
pass
finally:
CLIENTS.remove(websocket)
async def main():
async with websockets.serve(handler, "0.0.0.0", 8080, max_size=1536):
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())