Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonliu009/41133de9af648e4ba467f288be1a4939 to your computer and use it in GitHub Desktop.
Save simonliu009/41133de9af648e4ba467f288be1a4939 to your computer and use it in GitHub Desktop.
Python Tornado webserver that streams JPEGs (in img/) as MJPEG-Stream using asynchronous timed callbacks (yields), being able to handly many different streams at the same time
import tornado.ioloop
import tornado.web
import gen
import time
import os
import tornado
file_list = os.listdir("img")
counter = 0
def current_jpeg():
img = None
global counter
with open("img/" + file_list[counter]) as f:
img = f.read()
counter = (counter + 1) % len(file_list)
return img
class MJPEGHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
@tornado.gen.coroutine
def get(self):
ioloop = tornado.ioloop.IOLoop.current()
self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0')
self.set_header('Connection', 'close')
self.set_header( 'Content-Type', 'multipart/x-mixed-replace;boundary=--boundarydonotcross')
self.set_header('Expires', 'Mon, 3 Jan 2000 12:34:56 GMT')
self.set_header( 'Pragma', 'no-cache')
self.served_image_timestamp = time.time()
my_boundary = "--boundarydonotcross\n"
while True:
img = current_jpeg()
interval = 1.0
if self.served_image_timestamp + interval < time.time():
self.write(my_boundary)
self.write("Content-type: image/jpeg\r\n")
self.write("Content-length: %s\r\n\r\n" % len(img))
self.write(str(img))
self.served_image_timestamp = time.time()
yield tornado.gen.Task(self.flush)
else:
yield tornado.gen.Task(ioloop.add_timeout, ioloop.time() + interval)
application = tornado.web.Application([
(r"/", MJPEGHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment