-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
73 lines (62 loc) · 1.97 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env python
#
# Odroid fan control
#
# server.js
#
import asyncio
import websockets
import datetime
import socket
def nowTime():
return datetime.datetime.now().strftime("%H:%M:%S")
async def consumer(message):
print("consumer: ", message)
async def producer():
now = nowTime()
print("producer: ", now)
return(now)
async def consumer_handler(websocket):
try:
while True:
async for message in websocket:
await consumer(message)
except websockets.exceptions.ConnectionClosedOK:
pass
except Exception as err:
print(f"Unexpected {err=}, {type(err)=}")
print("End consumer_handler")
async def producer_handler(websocket):
try:
while True:
message = await producer()
await websocket.send(message)
await asyncio.sleep(1.0)
except websockets.exceptions.ConnectionClosedOK:
pass
except Exception as err:
print(f"Unexpected {err=}, {type(err)=}")
print("End producer_handler")
async def handler(websocket, path):
connectionId = websocket.remote_address[0]
try:
connectionId = format(socket.gethostbyaddr(connectionId))
except socket.herror:
pass
connectionId = nowTime() + " " + connectionId
print("Start connection: " + connectionId)
producer_task = asyncio.ensure_future(producer_handler(websocket))
consumer_task = asyncio.ensure_future(consumer_handler(websocket))
done, pending = await asyncio.wait(
[consumer_task, producer_task],
return_when=asyncio.FIRST_COMPLETED)
for task in pending:
task.cancel()
print("End connection: " + connectionId)
if __name__ == '__main__':
try:
start_server = websockets.serve(handler, "", 8001)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
except KeyboardInterrupt:
print("Keyboard interrupt, stopped.")