-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
55 lines (45 loc) · 1.63 KB
/
server.py
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
import websockets
import asyncio
import copy
import json
from modules.formats import Message
class Server:
clients = set()
async def register(self, websocket):
if len(self.clients) >= 2:
await websocket.send('Clients limit is 2 per server. You will not receive any messages')
return
self.clients.add(websocket)
pass
async def unregister(self, websocket):
print('Client disconnected')
self.clients.remove(websocket)
message = json.dumps(vars(Message('System', 1)))
await self.send_to_clients(message=message)
async def send_to_clients(self, message, websocket=None):
if self.clients:
new_clients = copy.copy(self.clients)
if websocket is not None:
new_clients.remove(websocket)
print(message)
try:
await asyncio.wait([client.send(message) for client in new_clients])
except:
pass
async def handler(self, websocket, path):
print('New client')
await self.register(websocket)
try:
await self.distribute(websocket)
finally:
await self.unregister(websocket)
async def distribute(self, websocket):
async for message in websocket:
await self.send_to_clients(message, websocket)
if __name__ == '__main__':
address = input('Enter IP address: ')
port = input('port: ')
server = Server()
start_server = websockets.serve(server.handler, address, int(port))
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()