-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
90 lines (69 loc) · 2.11 KB
/
client.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/python27
import tornado.platform.twisted
tornado.platform.twisted.install()
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.gen
import time, os.path
import multiprocessing
import monitor
import config
#!/usr/bin/env python -B
import json
import db
clients = []
db.setup()
class ViewHandler(tornado.web.RequestHandler):
def get(self):
self.render('views/index.html')
class DataHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self, datatype):
data = db.last(datatype, 50)
data.addCallback(self.on_response)
def on_response(self, data):
self.write(json.dumps(data))
self.finish()
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'New connection'
clients.append(self)
def on_message(self, message):
print message
def on_close(self):
print 'Connection closed'
clients.remove(self)
def main():
result_queue = multiprocessing.Queue()
m = monitor.Monitor(result_queue)
m.daemon = True
m.start()
# wait a second before sending first task
time.sleep(1)
print config.static_path
app = tornado.web.Application(
handlers=[
(r"/", ViewHandler),
(r"/ws", WebSocketHandler),
(r"/data/(\w+)", DataHandler)
], static_path = config.static_path
)
server = tornado.httpserver.HTTPServer(app)
server.listen(config.server_port)
print "Listening on port:", config.server_port
def poll_monitor():
try:
if not result_queue.empty():
result = result_queue.get()
for c in clients:
c.write_message(json.dumps(result))
except KeyboardInterrupt:
tornado.ioloop.IOLoop.instance().stop()
event_loop = tornado.ioloop.IOLoop.instance()
scheduler = tornado.ioloop.PeriodicCallback(poll_monitor, 10, io_loop = event_loop)
scheduler.start()
event_loop.current().start()
if __name__ == "__main__":
main()