我有一个服务器运行一个从设备读取数据的循环,我想把它们发送给所有在tornado上连接websocket的客户机。 我试着把循环放在open函数中,但是它不能处理关闭函数或新的连接。在
最好的做法是什么?在
#!/usr/bin/env python
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import socket
class MyWebSocketServer(tornado.websocket.WebSocketHandler):
def open(self):
print('new connection'+self.request.remote_ip)
try:
while True:
'''
read and send data
'''
except Exception,error:
print "Error on Main: "+str(error)
def on_close(self):
print('connection closed'+self.request.remote_ip)
application=tornado.web.Application([(r'/ws',MyWebSocketServer),])
if __name__=="__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8000)
print('start')
tornado.ioloop.IOLoop.instance().start()
谢谢
下面是一个完整的例子,说明如何在单独的线程中运行阻塞代码,并将消息广播到所有连接的客户端。在
相关问题 更多 >
编程相关推荐