我试图用Tornado websocket构建实时服务器统计信息。这是我的蟒蛇脚本
#!/usr/bin/python
.
.(imports)
.
# create logger
# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='/var/www/home/storage/app/logs/tornado.log',
filemode='w')
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
logger = logging.getLogger('realtime.py')
timeInterval= 2000 #Milliseconds
class WSHandler(tornado.websocket.WebSocketHandler):
def getCpuTemp( self ):
.
.
def getCpuUsage( self ):
.
.
def getRamUsage( self ):
.
.
def lr_temp(self):
.
.
def open(self):
logger.info('Connection Open')
#wss.append(self)
self.callback = PeriodicCallback(self.sendData, timeInterval)
self.callback.start()
def on_message(self, message):
try:
msg = json.loads(message)
except ValueError:
self.send_error("Invalid JSON")
logger.info('Invalid JSON')
return
#logger.info('message received: %s' % message)
logger.info('Message Received , JSON valid')
def sendData(self):
self.write_message(self.getCpuTemp() + ';' + self.lr_temp() + ';' + self.getCpuUsage() + ';' + self.getRamUsage())
def on_close(self):
logger.info('Connection Closed')
def check_origin(self, origin):
return True
application = tornado.web.Application([
(r'/ws', WSHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
myIP = socket.gethostbyname(socket.gethostname())
#print '*** Websocket Server Started at %s***' % myIP
tornado.ioloop.IOLoop.instance().start()
启动脚本后一切都很好,但是当我引用页面或发送消息时,脚本会进入此错误循环:
03-01 13:49 tornado.application ERROR Exception in callback <bound method WSHandler.sendData of <__main__.WSHandler object at 0xb644cab0>>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 1039, in _run
return self.callback()
File "/var/www/scripts/py/realtime.py", line 110, in sendData
self.write_message(self.getCpuTemp() + ';' + self.lr_temp() + ';' + self.getCpuUsage() + ';' + self.getRamUsage())
File "/usr/local/lib/python2.7/dist-packages/tornado/websocket.py", line 215, in write_message
raise WebSocketClosedError()
WebSocketClosedError
任何想法如何解决此错误?
在on_close
中,需要调用self.callback.stop()
。当连接关闭时,您可能仍会收到一个错误,但它不会进入循环。要使该错误也静音,请在调用周围使用 try/catch 来write_message
。