-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.py
64 lines (53 loc) · 2.16 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import os
import tornado.ioloop
import tornado.web
import tornado.gen
import tornado.websocket
import tornado.httpserver
class StreamHandler(tornado.web.RequestHandler):
def __init__(self, *args, **kwargs):
self.cam = kwargs.pop('cam')
super(StreamHandler, self).__init__(*args, **kwargs)
@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=frame')
self.set_header('Pragma', 'no-cache')
while self.cam.running and not self._finished:
try:
self.write(b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + self.cam.current_frame + b'\r\n')
yield tornado.gen.Task(self.flush)
except Exception as ex:
print(ex)
self.cam.newframe_notify.wait()
self.cam.newframe_notify.clear()
print('Request {0} finished!'.format(self.request))
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print('[WS] Connection was opened.')
def on_message(self, message):
print('[WS] Incoming message:', message)
def on_close(self):
print('[WS] Connection was closed.')
class WebServer():
def __init__(self, cam, port, address=""):
self.cam = cam
self.port = port
self.address = address
def start(self):
try:
application = tornado.web.Application([
(r"/aframe/(.*)", tornado.web.StaticFileHandler, {"path":os.path.join(os.path.dirname(__file__), "static")}),
(r'/ws', WSHandler),
(r'/stream', StreamHandler,{'cam':self.cam}),
])
self.http_server = tornado.httpserver.HTTPServer(application)
self.http_server.listen(self.port,self.address)
self.main_loop = tornado.ioloop.IOLoop.instance()
print("Tornado Server started")
self.main_loop.start()
except:
print("Tornado Server stopped.")