title: python - handle tornado connections into while loop
body: <p>I have a server running a loop that reads data from a device and I want to send them to all clients who connect on a websocket on tornado.
  I tried putting the loop inside the open function but then it can't handle on_close function or new connections.</p>
  
  <p>What is best practice to do that?</p>
  
  <pre><code>#!/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()
  </code></pre>
  
  <p>Thanks</p>