Created
November 24, 2014 11:23
-
-
Save mstaflex/c346b02b215e4099d09b 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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