-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathws_server.py
More file actions
33 lines (25 loc) · 908 Bytes
/
ws_server.py
File metadata and controls
33 lines (25 loc) · 908 Bytes
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
import logging
import asyncio
from websockets import WebSocketServerProtocol
import websockets
logging.basicConfig(level=logging.INFO)
class Server:
async def unregister(self, ws: WebSocketServerProtocol) -> None:
logging.info(f"disconnected {ws.remote_address}")
async def send_to_client(self, ws: WebSocketServerProtocol, msg: str) -> None:
await ws.send(msg)
async def distribute(self, ws: WebSocketServerProtocol) -> None:
async for msg in ws:
logging.info(f"got msg: {msg}")
await self.send_to_client(ws, "OK: " + msg)
async def ws_handler(self, ws: WebSocketServerProtocol, uri: str) -> None:
try:
await self.distribute(ws)
finally:
await self.unregister(ws)
if __name__ == '__main__':
server = Server()
start_server = websockets.serve(server.ws_handler, 'localhost', 1234)
loop = asyncio.get_event_loop()
loop.run_until_complete(start_server)
loop.run_forever()