Advertisement
Guest User

Untitled

a guest
Apr 1st, 2020
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. import asyncio, websockets, logging, os, binascii
  2.  
  3. logging.basicConfig()
  4.  
  5. SERVER_IP = '192.168.1.2';
  6. SERVER_PORT = 4441
  7.  
  8. class WebSocketsServer:
  9.  
  10.         def __init__(self, ip, port):
  11.                 self.clients = {}
  12.                 self.ip = ip
  13.                 self.port = port
  14.  
  15.         async def start(self):
  16.                 await websockets.serve(self.listen, self.ip, self.port)
  17.  
  18.         # end __init__
  19.  
  20.         async def listen(self, websocket, path):
  21.                 id = self.generate_id(16)
  22.                 self.clients[id] = websocket
  23.  
  24.                 await self.handle_client(id, websocket)
  25.  
  26.         # end listen
  27.  
  28.         async def handle_client(self, id, websocket):
  29.                 print(id + ' connected')
  30.  
  31.                 while True:
  32.                         try:
  33.                                 data = await websocket.recv()
  34.                                 print(id + ': ' + data)
  35.  
  36.                         except websockets.exceptions.WebSocketException:
  37.                                 print(id + ' disconnected')
  38.                                 await websocket.close()
  39.                                 break
  40.  
  41.         # end handle_client
  42.  
  43.         def generate_id(self, len):
  44.                 id = None
  45.  
  46.                 while id is None or id in list(self.clients):
  47.                         id = binascii.b2a_hex(os.urandom(int(len / 2))).decode(encoding='utf-8')
  48.  
  49.                 return id
  50.  
  51.         # end generate_id
  52.  
  53. server = WebSocketsServer(SERVER_IP, SERVER_PORT)
  54.  
  55. asyncio.get_event_loop().run_until_complete(server.start());
  56. asyncio.get_event_loop().run_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement