Python 3 Сервер с резьбовыми веб-сокетами
Я создаю серверное приложение Websocket в Python 3. Я использую эту реализацию:https://websockets.readthedocs.io/
В основном я хочу управлять несколькими клиентами. Также я хочу отправить данные из 2 разных потоков (один для GPS + один для IMU). Поток GPS обновляется с частотой 1 Гц, а поток с IMU обновляется с частотой 25 Гц.
Моя проблема в методе MSGWorker.sendData: как только я раскомментирую строку @ asyncio.coroutine и получаю из websocket.send ('{"GPS": "% s"}'% data), весь метод ничего не делает (нет печати («Отправить данные: foo») в терминал)
Однако с этими двумя комментариями мой код работает так, как я ожидаю, за исключением того, что я ничего не посылаю через веб-сокет.
Но, конечно, моя цель - отправлять данные через веб-сокет, я просто не понимаю, почему это не работает? Любая идея ?
server.py
#!/usr/bin/env python3
import signal, sys
sys.path.append('.')
import time
import websockets
import asyncio
import threading
connected = set()
stopFlag = False
class GPSWorker (threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.data = 0
self.lastData = 0
self.inc = 0
# Simulate GPS data
def run(self):
while not stopFlag:
self.data = self.inc
self.inc += 1
time.sleep(1)
def get(self):
if self.lastData is not self.data:
self.lastData = self.data
return self.data
class IMUWorker (threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.data = 0
self.lastData = 0
self.inc = 0
# Simulate IMU data
def run(self):
while not stopFlag:
self.data = self.inc
self.inc += 1
time.sleep(0.04)
def get(self):
if self.lastData is not self.data:
self.lastData = self.data
return self.data
class MSGWorker (threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
while not stopFlag:
data = gpsWorker.get()
if data:
self.sendData('{"GPS": "%s"}' % data)
data = imuWorker.get()
if data:
self.sendData('{"IMU": "%s"}' % data)
time.sleep(0.04)
#@asyncio.coroutine
def sendData(self, data):
for websocket in connected.copy():
print("Sending data: %s" % data)
#yield from websocket.send('{"GPS": "%s"}' % data)
@asyncio.coroutine
def handler(websocket, path):
global connected
connected.add(websocket)
#TODO: handle client disconnection
# i.e connected.remove(websocket)
if __name__ == "__main__":
print('aeroPi server')
gpsWorker = GPSWorker()
imuWorker = IMUWorker()
msgWorker = MSGWorker()
try:
gpsWorker.start()
imuWorker.start()
msgWorker.start()
start_server = websockets.serve(handler, 'localhost', 7700)
loop = asyncio.get_event_loop()
loop.run_until_complete(start_server)
loop.run_forever()
except KeyboardInterrupt:
stopFlag = True
loop.close()
print("Exiting program...")
client.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
</body>
</html>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:7700", 'json');
ws.onmessage = function (e) {
var data = JSON.parse(e.data);
console.log(data);
};
</script>
Спасибо тебе за помощь