Web套接字服务器的后台任务

时间:2014-07-01 16:27:41

标签: python autobahn python-asyncio

我想运行一个Web套接字服务器来提供一个覆盆子pi板的接口。具体来说,我想连续轮询传感器,参考变量处理来自Web套接字的输入,然后根据需要运行电机。

我以为我可以在子类__init__上使用WebSocketServerProtocol方法来执行轮询传感器和运行电机,并使用onMessage()方法处理来自客户端并返回系统的当前状态,但是我担心我没有正确理解WebSocketServerProtocolWebSocketServerFactory,我似乎无法让后台任务在连接中保持不变。< / p>

实现我想要的最好方法是什么?也许高速公路是过度的 - 在连接的计算机上只会有一个客户端,因此这种意义上的并发性不是问题。我只是希望电机和轮询传感器的运行不会阻塞以确保平稳运行。

1 个答案:

答案 0 :(得分:1)

您可以做的一件事是在不同的线程上运行传感器轮询和http / motor模块。

我认为您可以轻松解决问题,而无需为高速公路创建不必要的额外依赖项。

检查Python提供的SimpleHTTPServer(python 2.x)或http.server(python 3.x)模块。

您只需要对SimpleHTTPRequestHandler类进行子类化,以提供执行该工作的do_POST()do_GET()方法(它们取代您的onMessage() (如下):

import threading

from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer   import BaseHTTPServer

def poll():
   ...

class MyHandler(SimpleHTTPRequestHandler):
    protocol_version = "HTTP/1.0"
    def do_POST(self):
        if all_ok_with_the_request:
            motor.run()
    def do_GET(self):
        self.wfile.write("status = {}".format(status))

def runServer(address, port):
   httpd = BaseHTTPServer( (address, port), MyHandler )
   httpd.serve_forever()

threading.Thread(target=poll).run()
threading.Thread(target=runServer).run()