This repository was archived by the owner on May 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
48 lines (42 loc) · 1.19 KB
/
server.py
File metadata and controls
48 lines (42 loc) · 1.19 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
from traceback import print_exception
import asyncio
import json
import websockets
connections = []
# Daemon
async def daemon(sock):
print(f"\"{sock.remote_address[0]}\" connected.")
connections.append(sock)
try:
while True:
data = await sock.recv()
print(f"\"{sock.remote_address[0]}\": \"{data}\"")
for sockc in connections:
if sockc.closed != True:
await sockc.send(json.dumps(
{
"nickname": sock.remote_address[0],
"msg": data
}
))
except websockets.exceptions.ConnectionClosedOK:
pass
except BaseException as err:
print_exception(err)
print(f"\"{sock.remote_address[0]}\" closed.")
connections.remove(sock)
# Socket server
HOST = '0.0.0.0'
PORT = 3500
print("Ready")
async def main():
async with websockets.serve(daemon, HOST, PORT):
await asyncio.Future()
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
except BaseException as err:
print_exception(err)
print("Bye")