【发布时间】:2018-02-19 07:56:47
【问题描述】:
我在一个记录温度等的树莓派上运行一个网络服务器。 我在 Tornado 中使用 websockets 与我的客户进行通信。 我希望客户端能够控制服务器何时通过套接字发送数据。
我的想法是,当客户端连接并说它已准备好时,服务器将启动一个循环,它每秒记录一次临时文件。但我需要这个循环异步运行。这就是我遇到麻烦的地方。我尝试按照示例进行操作,但无法正常运行。
class TemperatureSocketHandler(tornado.websocket.WebSocketHandler):
@gen.coroutine
def async_func(self):
num = 0
while(self.sending):
num = num + 1
temp = self.sense.get_temperature()
yield self.write_message(str(temp))
gen.sleep(1)
def open(self):
print("Temperature socket opened")
self.sense = SenseHat()
self.sense.clear()
self.sending = False
def on_message(self, message):
if(message == "START"):
self.sending = True
if(message == "STOP"):
self.sending = False
tornado.ioloop.IOLoop.current().spawn_callback(self.async_func(self))
但是当我运行这个时我得到一个错误:
ERROR:tornado.application:Exception in callback functools.partial(<function wrap.<locals>.null_wrapper at 0x75159858>)
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.5/site-packages/tornado/ioloop.py", line 605, in _run_callback
ret = callback()
File "/home/pi/.local/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
TypeError: 'Future' object is not callable
【问题讨论】:
-
请修正缩进。你在
on_message中打电话给spawn_callback吗? -
抱歉,已修复
标签: python asynchronous websocket webserver tornado