public
Last active

sockjs-tornado with tornado.gen interface.

  • Download Gist
async.py
Python
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
# -*- coding: utf-8 -*-
 
from tornado import ioloop, web, gen, httpclient
 
from sockjs.tornado import SockJSConnection, SockJSRouter
 
 
class IndexHandler(web.RequestHandler):
"""Regular HTTP handler to serve the ping page"""
def get(self):
self.render('index.html')
 
 
# Out broadcast connection
class GrabConnection(SockJSConnection):
def on_message(self, msg):
print '1 - Making request'
self.handle_request(msg)
print '2 - Returned from on_message'
 
@gen.engine
def handle_request(self, url):
client = httpclient.AsyncHTTPClient()
response = yield gen.Task(client.fetch, url)
self.send(repr(response.headers))
print '3 - Sent data to client'
 
 
GrabRouter = SockJSRouter(GrabConnection, '/grab')
 
 
if __name__ == "__main__":
import logging
logging.getLogger().setLevel(logging.DEBUG)
 
# Create application
app = web.Application(
[(r"/", IndexHandler)] +
GrabRouter.urls
)
app.listen(8080)
 
print 'Listening on 0.0.0.0:8080'
 
ioloop.IOLoop.instance().start()
index.html
HTML
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
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script>
$(function() {
var conn = new SockJS('http://localhost:8080/grab');
 
conn.onmessage = function(e) {
$('<div/>').text(e.data).appendTo($('#msg'));
$('#msg').append('<hr/>');
}
 
$('#grab').click(function() {
conn.send('http://www.google.com/');
return false;
});
});
</script>
</head>
<body>
<h3>Grab it!</h3>
<div id="msg"></div>
</body>
<a id="grab" href="#">Grab!</a>
</html>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.