Python 3线程websockets服务器 [英] Python 3 Threaded websockets server

查看:138
本文介绍了Python 3线程websockets服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python 3构建Websocket服务器应用程序.我正在使用以下实现: https://websockets. readthedocs.io/

I'm building a Websocket server application in python 3. I'm using this implementation: https://websockets.readthedocs.io/

基本上我想管理多个客户端. 我也想从2个不同的线程发送数据(一个用于GPS +一个用于IMU) GPS线程以1Hz刷新,而IMU线程以25Hz刷新

Basically I want to manage multiple client. Also I want to send data from 2 different thread (one for GPS + one for IMU) GPS thread is refreshed 1Hz, while IMU thread is refresh at 25Hz

我的问题出在MSGWorker.sendData方法中:一旦我取消注释@ asyncio.coroutine行并从websocket.send('{"GPS":%s"}'%data)产生时,整个方法就什么都不做(在终端中没有print(发送数据:foo"))

My problem is in MSGWorker.sendData method: as soon as I uncomment the line @asyncio.coroutine and yield from websocket.send('{"GPS": "%s"}' % data) the whole method does nothing (no print("Send data: foo") in terminal)

但是用这两行注释,我的代码可以正常工作,只是我没有通过网络套接字发送任何东西.

However with these two line commented my code works as I expect except that I send nothing through the websocket.

但是,当然,我的目标是通过websocket发送数据,我只是不明白为什么它不起作用?有什么主意吗?

But, of course, my goal is to send data through the websocket, I just don't understand why it doesn't work ? Any idea ?

server.py

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

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>

感谢您的帮助

推荐答案

最后我明白了! 它需要Python 3.5.1(而我的发行版仅提供3.4.3)和websockets库的作者Aymeric的帮助(感谢他).

Finally I got it ! It required Python 3.5.1 (while my distro provide only 3.4.3) and some help from Aymeric, the author of the websockets library (thanks to him).

#!/usr/bin/env python3
import signal, sys
sys.path.append('.')
import time
import websockets
import asyncio
import threading


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)
    self.connected = set()

  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)

  async def handler(self, websocket, path):
    self.connected.add(websocket)
    try:
      await websocket.recv()
    except websockets.exceptions.ConnectionClosed:
      pass
    finally:
      self.connected.remove(websocket)

  def sendData(self, data):
    for websocket in self.connected.copy():
      print("Sending data: %s" % data)
      coro = websocket.send(data)
      future = asyncio.run_coroutine_threadsafe(coro, loop)



if __name__ == "__main__":
  print('aeroPi server')
  gpsWorker = GPSWorker()
  imuWorker = IMUWorker()
  msgWorker = MSGWorker()

  try:
    gpsWorker.start()
    imuWorker.start()
    msgWorker.start()

    ws_server = websockets.serve(msgWorker.handler, '0.0.0.0', 7700)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(ws_server)
    loop.run_forever()
  except KeyboardInterrupt:
    stopFlag = True
    #TODO: close ws server and loop correctely
    print("Exiting program...")

关于, 克莱姆特

这篇关于Python 3线程websockets服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆