-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlive.py
72 lines (63 loc) · 1.91 KB
/
live.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
65
66
67
68
69
70
71
72
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.template
import struct
import sys
from StringIO import StringIO
import threading
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
self.set_nodelay(True)
self.write_message("The server says: 'Hello'. Connection was accepted.")
def select_subprotocol(self,protocols):
print "protocols",len(protocols),protocols
if len(protocols) > 0:
return protocols[0]
else:
return
def on_message(self, message):
# FUTURE:
# push in main thread queue
# let it execute
# respond with error once
print "got<",message,">"
buffer = StringIO()
sys.stdout = buffer
try:
exec message
except Exception ,e:
self.write_message("Exception " + str(e),binary=False)
return
sys.stdout = sys.__stdout__
self.write_message("Ok " + buffer.getvalue(),binary=False)
def check_origin(self,origin):
print "check origin",origin
return True
def on_close(self):
print 'connection closed...'
application = tornado.web.Application([
(r'/x', WSHandler),
(r"/", web.RedirectHandler, {"url": "/index.html"}),
(r"/(.*)", tornado.web.StaticFileHandler, {"path": "."}),
])
#WebSocket connection to 'ws://127.0.0.1:8000/' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received
#https://github.com/gdi2290/angular-websocket/issues/13
def _server_runner(app):
print "started"
app.listen(8000)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
th = threading.Thread(target = _server_runner, args = [application])
th.daemon = True
th.start()
ev = threading.Event()
ev.clear()
try:
# some non-blocking looping in main thread
while not ev.isSet():
print "Main loop"
ev.wait(30)
except KeyboardInterrupt:
pass
print "good bye"